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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:43:24  来源:igfitidea点击:

Eloquent: hasNot with parameter

laraveleloquent

提问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 Postmodel with a whereDoesnthaverelationship. 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 commentsis defined on the Postmodel as:

这将假设commentsPost模型上定义为:

public function comments(){
  return $this->hasMany(Comment::class);
}

Basically, if the commentsrelationship with the check for that $userIdreturns 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');