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

时间:2017-02-26 09:00:48

标签: laravel laravel-5 eloquent laravel-5.4

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

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

在此查询的结果中,我获得了嵌套集合:

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

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

2 个答案:

答案 0 :(得分:1)

您可以尝试以下方式简化它:

$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:关于效率,我不能说,但是,这应该有效。

答案 1 :(得分:1)

你可以采用相反的方式来获得这样的公告:

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

这显然是伪代码,因为我不知道你的关系的确切名称,但是这样的东西应该有用,你不需要任何循环。