Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent: hasNot with parameter

I have the following eloquent models:

User | id

Post | id

Comment | id | post_id | user_id

Using eloquent, how can I fetch all Posts which a specific User hasn't commented yet?

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);
}
like image 867
Frooplet Avatar asked Sep 25 '17 19:09

Frooplet


2 Answers

The way I would do this is by querying the Post model with a whereDoesnthave relationship. In your 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 would assume that comments is defined on the Post model as:

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.

like image 118
Tim Lewis Avatar answered Nov 10 '22 12:11

Tim Lewis


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();
like image 7
Morteza Rajabi Avatar answered Nov 10 '22 12:11

Morteza Rajabi