vendredi 4 décembre 2015

Eloquent/Laravel: Nested lazy eager loading, but return multiple last model's relations

Apologies if the title does not make much sense, but here's what I've got and what I'd like to achieve.

There's a restaurant's menu, which is structured like this:

Restaurant
|- category 1
   |- subcategory 1
   |- subcategory 2
      |- item 1
         * price levels:
         |- price level 1
         |- price level 2
         * modifiers groups:
         |- group 1
            |- modifier 1
            |- modifier 2

The goal is to write the most efficient way (in terms of database queries) to get the entire menu (served as JSON via API), but there's a catch: I need both price levels AND modifiers for each item.

The most efficient way that I came up with is:

Part 1: chain all the way up to item's modifiers (because they're more nested than price levels):

$this->restaurant->load('categories.subcategories.items.modifier_groups_enabled.modifiers_enabled');

Part 2: Before starting the loop through categories/subcategories/items, I "manually" get all price levels that belong to all items in a restaurant, then I put them into an array, grouped by item's id. Then, while looping through the menu, I just grab the $price_levels[$item->id] as an array of item's price levels.

With nothing cached, the entire request is complete in 7 queries, which is OK, but the 'dirty' way of preparing price levels is bothering me a bit :)

If I cut the nested eager loading up to items only, then get each item's price levels and modifiers ($item->load[...]), database queries pile up since each item runs its own ones to get price levels and modifier groups/modifiers.

So, the question is: Can $this->restaurant->load('...') be written in such a way that it also returns all items' price levels AND modifiers?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire