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 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动