Amo
Amo

Reputation: 2944

Laravel simple constraint on eager load

I have a user model, which belongs to one site. One site can have many users.

User table

Site table

The relationship is defined in User as follows:

public function site()
{
    return User::belongsTo('App\CompanySite', 'company_site_id', 'id');
}

I want to simply get all users assigned to a site (lets say with a site ID of 1).

$users = \App\User::with(array('site' => function($query)
{
$query->where('id', '=', 1);

}))->get();
dd(count($users));

However this is returning all of the users irrespective of their site.

Upvotes: 2

Views: 84

Answers (1)

Matt Burrow
Matt Burrow

Reputation: 11097

You are getting all the users that is why, with the use of ->get();.

Use the whereHas method. This will query your relationship and return only the models that have the relation results you are wanting/querying;

$users = User::whereHas('site', function($q)
{
    $q->where('id', '=', 1);

})->get();

So Users that have site with an id of 1 will be returned in this instance.

Upvotes: 1

Related Questions