采摘渴望加载Laravel 5.2
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了采摘渴望加载Laravel 5.2相关的知识,希望对你有一定的参考价值。
在使用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,但我没有找到成功的答案。
答案
您必须在查询后拔出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');
}
以上是关于采摘渴望加载Laravel 5.2的主要内容,如果未能解决你的问题,请参考以下文章