duanhuihui2705 2018-08-03 22: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-04 00: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条)

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退