Search code examples
phplaravelnestedmodels

Laravel: how to get nested models


Could not you to direct me in right way.

I have four models: "Item" belongs to several "Category" belongs to "Shop" belongs to "City"

How can i select Item with all nested models (for json response, for example, it is not important).

In other words, i want to get sctructure like that:

 item
  category_1
    shop_1
    shop_2
      city_1
  category_2

I able to get categories by $item->with('categories') statement, but how i can get nested items in category (shops, and then - cities).

Thank you for your help!


Solution

  • Nested Eager Loading

    To eager load nested relationships, you may use "dot" syntax.

    So to achieve that, just do this:

    $item->with('categories', 'categories.shop', 'categories.shop.city');