[英]Laravel get one value from eager load
我在Laravel中得到了这个查询,该查询返回所有带有一些额外信息的论坛:
return Forum::with(['messages.user' => function($query){
$query->select('id', 'name');
}])->withCount('messages')->paginate(10);
但现在它也渴望加载所有相关消息,但我只需要消息中的作者。 我怎么能得到这个结果?
不用急于加载,
//针对特定论坛
//获取论坛实体
$forum = Forum::find($id);
//获取其消息作为集合
$forumMessages = $forum->messages;
//遍历Collection上的每个消息以查找其作者。 这将根据您在消息表中存储的'author_id'在User模型中查找id。$ forumMessages集合现在将具有作者的名字。 这只是给您一个想法。 根据您的需求进行结构设计。
$forumMessages->each(function ($message){
$message->author = User::find($message->author_id)->name;
});
尝试使用
return Forum::with([
'messages' => function ($messages) {
return $messages->with([
'user' => function ($user) {
return $user->select('id', 'name');
}
])->select('id', 'author'); // you get author from messages
}
])->withCount('messages')->paginate(10);
这也渴望加载,但您只会获得id
和author
。 需要id
才能与用户建立关系。
假设您用于Message
模型的表是messages
,并且具有forum_id
和user_id
列,并且您的User
模型的表是users
您只需定义一个belongsToMany
并以这种方式获取信息:
public function users()
{
return $this->belongsToMany(User::class, 'messages')->distinct();
}
然后:
return Forum::with(['users' => function($query){
$query->select('users.id', 'users.name');
}])->withCount('messages')->paginate(10);
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.