Eloquent: hasNot with parameter

I have the following eloquent models:

User | Identifier

Message | Identifier

Comment | id | post_id | user ID

Using eloquent, how can I get all posts that a specific user has not yet commented on?

I have tried so far:

In the model Message :

public function noCommentOf(User $user) { $this->hasNot('App\Comment')->commentOf($user); }

In the model Comment :

public function commentOf($query, User $user) { return $query->where('user_id', '=', $user->id); }

+4
source share
3 answers

The way I did this is querying a model Postwith a relation whereDoesnthave. In the controller:

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 suggests that it commentsis defined in the model Postas follows:

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

, comments $userId a Collection, .

+3

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

$posts = Post:: whereDoesntHave('comments', function ($query) use ($userId) {
    $query->where('user_id', $userId);
});

$posts = Post::has('comments', '=', 0)->get();
+1

I think:

$user->post()->leftJoin('comments', 'posts.id', '=', 'comments.post_id')->whereNull('comments.id');
0
source

Source: https://habr.com/ru/post/1686366/


All Articles