首页 > 解决方案 > Laravel 获取所有通过帖子评论帖子的用户

问题描述

我一直试图让所有评论帖子的用户

$post->comments()->user() //does not work
$post->comments()->load('user', function($q) { $q->select('email'); }));//does not work
$post->comments()->with('user')->get() //worked but not getting the user as result (still need to loop)

但我得到一个 BadMethodCallException 这是模型

//Comment Model
public function user(){
    return $this->belongsTo(User::class);
}
public function post(){
 return $this->belongsTo(Post::class);
}


//User Model
public function comments(){
     return $this->hasMany(Comment::class);
}
public function posts(){
     return $this->hasMany(Post::class);
}

//Post Model
public function user(){
      return $this->belongsTo(User::class);
}
public function comments(){
     return $this->hasMany(Comment::class);
}

标签: laraveleloquentlaravel-8

解决方案


我找到了答案(我认为这是一个重复的问题,但无论如何)

Laravel 获取用户评论的所有帖子

相反,我使用这个

$post->whereHas('comments', function($query) use($user) {
     $query->where('id',$user->id);
 })->get();

推荐阅读