【问题标题】:Laravel - join comments ,posts, usersLaravel - 加入评论、帖子、用户
【发布时间】:2018-08-03 22:00:06
【问题描述】:

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

控制器:

$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');
}

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

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您的评论模型:

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

    暗示数据库中的用户条目将具有comment_id 字段。但它实际上应该在comments 数据库表中有一个user_id 字段:

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

    现在您也可以立即加载 cmets 的作者:

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

    【讨论】:

      【解决方案2】:

      我并没有深入探讨建立一种雄辩的关系。我希望您已正确设置它。

      让我们专注于查询:

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

      注意:未经测试。试试看。

      【讨论】:

      • 你也可以只用`Post::with('cmets', 'cmets.user', 'user')
      • 是的,我知道,但为了简单起见,我更喜欢使用这种方式。 :) 谢谢。
      猜你喜欢
      • 1970-01-01
      • 2017-07-29
      • 2018-08-16
      • 1970-01-01
      • 2016-05-27
      • 2014-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多