如何从嵌套的 Eager Loading Laravel 中获取对象?

How to get object from nested Eager Loading Laravel?

在查询中我使用嵌套预加载:

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

在这个查询的结果中,我得到了嵌套集合:

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

如何快速获取最后一个嵌套对象announcements

您可以尝试以下操作来简化它:

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

$announcements = collection([]);

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

这里的想法或假设是,对于每个类别,categoryAnn 是一个并且可以有 one-many 个公告。

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

你可以用相反的方式只得到这样的通知:

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

这显然是伪代码,因为我不知道你的关系的确切名称,但像这样的东西应该可以工作,你在这里不需要任何循环。