简体   繁体   English

Laravel从热切的负载中获得一个价值

[英]Laravel get one value from eager load

I've got this query in Laravel that's returning all forums with some extra information: 我在Laravel中得到了这个查询,该查询返回所有带有一些额外信息的论坛:

return Forum::with(['messages.user' => function($query){
    $query->select('id', 'name');
}])->withCount('messages')->paginate(10);

but now it eager loads all related messages as well but I only need the author from a message. 但现在它也渴望加载所有相关消息,但我只需要消息中的作者。 How could I get this result? 我怎么能得到这个结果?

Without eager loading, 不用急于加载,

//for a particular forum //针对特定论坛

//Get a forum entity //获取论坛实体

$forum = Forum::find($id);

// Get its messages as a Collection //获取其消息作为集合

$forumMessages = $forum->messages;

// Iterate over each message on the Collection to find its author. //遍历Collection上的每个消息以查找其作者。 This will look for id in the User model based on the 'author_id' stored by you in the message table.The collection $forumMessages will now have the author's name. 这将根据您在消息表中存储的'author_id'在User模型中查找id。$ forumMessages集合现在将具有作者的名字。 This is just to give you an idea. 这只是给您一个想法。 Structure accordingly to your needs. 根据您的需求进行结构设计。

 $forumMessages->each(function ($message){
  $message->author = User::find($message->author_id)->name;
});

Try using 尝试使用

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);

This also eager loads but you only get id and author . 这也渴望加载,但您只会获得idauthor id is needed to make the relationship with user. 需要id才能与用户建立关系。

Assuming the table you have for your Message model is messages and that it has the columns forum_id and user_id , and the table for your User model is users you could just define a belongsToMany and get the information that way: 假设您用于Message模型的表是messages ,并且具有forum_iduser_id列,并且您的User模型的表是users您只需定义一个belongsToMany并以这种方式获取信息:

public function users()
{
    return $this->belongsToMany(User::class, 'messages')->distinct();
}

then: 然后:

return Forum::with(['users' => function($query){
     $query->select('users.id', 'users.name');
}])->withCount('messages')->paginate(10);

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM