How to get object from nested Eager Loading Laravel?

拜拜、爱过 提交于 2019-12-01 12:23:10

问题


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.



来源:https://stackoverflow.com/questions/42466599/how-to-get-object-from-nested-eager-loading-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!