How to get object from nested Eager Loading Larave

2019-02-21 04:46发布

问题:

In query I use Nested Eager Loading:

$res = User::where("id", 1)->with("categories.categoryAnn.announcements")->get();

In result of this query I get nested collections:

Collection->User->categories->categoryAnn->announcements

How to shortly get last nested object announcements?

回答1:

You can do it the opposite way to get only announcements like this:

$announcements =  Announcement::whereHas('categoriesAnn', function($q) {
  $q->whereHas('categories, function($q) {
      $q->whereHas('user', function($q) {
          $q->where('id',1);
      });
  });
});

This is obviously pseudocode, because I don't know exact names of your relationships but something like this should work and you don't need any loops here.



回答2:

You can simplify it attempting the following:

$categories = User::find(1)->categories()->get(); //loads the categories alone

$announcements = collection([]);

foreach(categories as $category)
{
    $announcements->push($category->categoryAnn->announcements);
}

The idea or assumption here is that for each categories, categoryAnn is one and can have one-many announcements.

PS: about efficiency, I cannot really tell, but yeah, this should work.