laravel - 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);
}
解决方案
我找到了答案(我认为这是一个重复的问题,但无论如何)
相反,我使用这个
$post->whereHas('comments', function($query) use($user) {
$query->where('id',$user->id);
})->get();
推荐阅读
- powershell - 我们可以在并行容器中运行两个进程任务吗,比如第一个线程中的 350 个文件并在第二个线程中休息
- wpf - 带有多图标的 WPF 应用程序
- html - css中是否有任何确切的先前节点?
- python - MPESA C2B 验证和确认交易无响应
- json - 在 Solr 中发布时出现未知字段错误
- php - 导出excel或csv大行和动态列
- django - 如何在模板中转储上下文?
- python - 模板中的 Django 邮箱刷新按钮
- ios - 如何使用 Swift 更新 CoreData 数据
- angular - Angular:cdk-virtual-scroll + 自动完成 - cdk-overlay-pane 问题