laravel Eloquent:hasNot 带参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46413064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eloquent: hasNot with parameter
提问by Frooplet
I have the following eloquent models:
我有以下雄辩的模型:
User| id
用户| ID
Post| id
发布| ID
Comment| id | post_id | user_id
评论| 身 | post_id | 用户身份
Using eloquent, how can I fetch all Posts which a specific User hasn't commented yet?
使用 eloquent,如何获取特定用户尚未评论的所有帖子?
I tried so far:
到目前为止我尝试过:
In Model Post:
在模特帖子中:
public function noCommentOf(User $user) {
$this->hasNot('App\Comment')->commentOf($user);
}
In Model Comment:
在模型评论中:
public function commentOf($query, User $user) {
return $query->where('user_id', '=', $user->id);
}
回答by Tim Lewis
The way I would do this is by querying the Post
model with a whereDoesnthave
relationship. In your controller:
我这样做的方法是通过关系查询Post
模型whereDoesnthave
。在您的控制器中:
public function getPostsWithoutCommenter(){
$userId = 1; // Could be `$user`, `use($user)` and `$user->id`.
$posts = \App\Post::whereDoesntHave("comments", function($subQuery) use($userId){
$subQuery->where("user_id", "=", $userId);
})->get();
}
This would assume that comments
is defined on the Post
model as:
这将假设comments
在Post
模型上定义为:
public function comments(){
return $this->hasMany(Comment::class);
}
Basically, if the comments
relationship with the check for that $userId
returns a Collection
, it would be ignored from the result set.
基本上,如果comments
与检查的关系$userId
返回 a Collection
,它将从结果集中被忽略。
回答by Morteza Rajabi
Post model
后模型
public function comments()
{
return $this->hasMany(Comment::class)
}
Then get posts
然后获取帖子
$posts = Post:: whereDoesntHave('comments', function ($query) use ($userId) {
$query->where('user_id', $userId);
});
To get posts with no comments
获取没有评论的帖子
$posts = Post::has('comments', '=', 0)->get();
回答by Kornél Takó
I think:
我认为:
$user->post()->leftJoin('comments', 'posts.id', '=', 'comments.post_id')->whereNull('comments.id');