Support the ongoing development of Laravel.io →
Eloquent Database

Hi all.

I have 3 tables in Laravel: doctors, clinics and clinic_doctors. Doctors have relation:

public function clinics()
{
	return $this->belongsToMany('\App\Models\Clinic', 'clinic_doctor');
}

And I try to get all doctors with TOP clinics:

$doctors = Doctor::with(['clinics' => function($query){
    	            $query->where('clinics.top', true);
            	}])
	->where('doctors.active', 1)
	->select('doctors.id')
	->orderByRating()
	->get();

(instead TRUE I've tried 'true', 1, '1' - with the same result)

This query returns 1662 records - it's wrong result! But when I get SQL query from:

dd(\DB::getQueryLog());

and execute it directly in MySQL it returns 119 records. And this is right result.

What am I doing wrong with Eloquent?

Last updated 3 years ago.
0
Solution

Found solution: have changed "with" to "whereHas", and now it works!

Doctor::whereHas('clinics', function($query){
	$query->where('clinics.top', true);
}])
Last updated 6 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

PV pv Joined 21 Mar 2019

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.