0

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.

christianleroy
  • 1,084
  • 5
  • 25
  • 39

1 Answers1

2

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();
Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157
  • Although I don't quite get the difference between whereHas and the eager loading constraint. – christianleroy Oct 14 '14 at 02:18
  • The difference is this: `with` loads all assets but only filtered related classifications, while `whereHas` filters assets by related classifications (and doesn't load the latter at all, unless you use `with` again..) – Jarek Tkaczyk Oct 14 '14 at 07:30