首页 > 解决方案 > Laravel - 加入评论、帖子、用户

问题描述

我正在尝试返回每个帖子的作者,以及每个帖子的作者评论。这就是我所做的:

控制器:

$posts = Post::with('comments', 'user')->latest()->paginate(3);

邮政模型:

public function comments() {
    return $this->hasMany('App\Comment');
}

public function user() {
    return $this->belongsTo('App\User');
}

评论模型:

public function users() {
    return $this->hasOne('App\User');
}

这将返回每个帖子及其作者和评论,但不返回评论的作者。
我还应该怎么做??

标签: phplaravel

解决方案


我不会更深入地建立一种雄辩的关系。我希望您已正确设置它。

让我们专注于查询:

Post::with('comments', 'user') -> Returns post with comments and who created it. Which is correct but now what you want.

更新您的代码

$posts = Post::with(['user', 
    'comments' => function($q) {
        $q->with('user'); //Rename users to user in eloquent model. }
    ])->latest()->paginate(3);

注意:未测试。试试看。


推荐阅读