christianleroy
christianleroy

Reputation: 1104

Unexpected Results in Laravel Eager Loading With Constraints

I have two tables: assets and asset_classifications. The tables have one-to-many relationship, where an asset has one asset classification, and asset_classifications have many assets.

I'm trying to run a query to get all assets which has an asset_classification name of "laptops", for example. I'm trying to do this by running this eager load with a constraint:

$laptops = Asset::with(array('classification'=>function($query){
    $query->where("name","=","laptops");
}))->get();

foreach($laptops as $laptop){
    echo $laptop->serial_number."<br/>";
}

name is a column from asset_classifications table. I already formed the one-to-many relationship by setting up the needed methods for my Asset and AssetClassification models.

The problem with my eager load is that it gets all the assets, seeming to ignore my eager loading constraint which tries to get only the "laptops". I think the problem is in my code or my understanding of eager loading, but I don't know which. I'm still new to this and I hope someone can help me.

Upvotes: 0

Views: 194

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81167

with is used to filter related models, while you need whereHas for filtering main queried model by related table constraints:

$laptops = Asset::whereHas('classification', function ($query) {
    $query->where("name","=","laptops");
})->get();

Upvotes: 2

Related Questions