duanhuihui2705 2018-08-03 14:00
浏览 21
已采纳

Laravel - 加入评论,帖子和用户

I'm trying to return every posts with each one's author, and also every post's comments with it's author. this is what i did:

The controller:

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

The Post model:

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

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

The Comment model:

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

This returns every post with their authors and the comments but not the comment's author.
what else should i do??

  • 写回答

2条回答 默认 最新

  • douquanjie9326 2018-08-03 16:35
    关注

    Your Comment model:

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

    Implies that a user entry in database would have a comment_id field. But instead it should really have a user_id field in the comments database table:

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

    Now you can eager load authors of comments as well:

    $posts = Post::with('comments.user', 'user')->latest()->paginate(3);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部