采摘渴望加载Laravel 5.2

时间:2018-02-16 13:41:28

标签: laravel-5.2 eager-loading

在使用Laravel 5.2进行查询时,如何获取急切加载的关系?

$users = User::with(['posts' => function($query){
       $query->pluck('id');
       }])->get();

我希望回复只是用户帖子ID的数字,如下所示:

[{user: Blabel, posts: [24,25,26]},
 {user: Kraker, posts: [75,76,77]}]

我现在得到的是帖子表中的所有字段:

[{user:Blabel,
  posts:[{id:24, name: "blabla", text: "bleble"},
         {id:25, name: "blablabla", text: "blebleble"},
         {id:26, name: "blablablo", text: "blebleblo"},
         ...
        ]},
  {user:Kraker,
   posts:[{id:75, name: "krakra", text: "krekre"},
          {id:76, name: "krakrakra", text: "krekrekre"},
          {id:77, name: "krokro", text: "krekrekro"},
          ...
         ]}

我可以在Eager Loading Constraint中使用pluck吗? 问题与:Pluck Eager Loading Laravel 5.4相同,但我没有找到成功的答案。

1 个答案:

答案 0 :(得分:0)

您必须在查询后拔出ID:

$users = User::with(['posts' => function($query){
   $query->select('id', 'user_id'); // assuming it's a HasMany relationship
}])->get();
$users = $users->toArray();
foreach($users as $i => $user) {
    $users[$i]['posts'] = collect($user['posts'])->pluck('id');
}