nutzt
nutzt

Reputation: 2923

Laravel eloquent get conditional result in where

I have this table participations

| active   | customer_id   | doctor_id
| -------- | ------------- | ----------
| true     | 1             | 5         
| true     | 2             | 5         
| true     | 3             | 5         

I'm trying to get all the doctors except those who are already assigned to a customer.

The participation relation in my doctor model:

public function participations() {
  return $this->hasMany(Participation::class);
}

My doctors model have this scope method:

public function scopeOnlyAvailable($query, $customerId = 1) {
  return $query->whereHas('participations', function($query) use ($customerId) {
    $query->where('customer_id', '!=', $customerId);
  }
}

With this scope i don't get the dataset with the customer_id 1, but all other datasets. Thats the problem, because they contain the same doctor (which i dont want).

Upvotes: 1

Views: 118

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163788

Use the whereDoesntHave() method:

return $query->whereDoesntHave('participations', function($query) use ($customerId) {
    $query->where('customer_id', $customerId);
}

Upvotes: 1

Related Questions