Reputation: 8096
What is the correct way to find a related object based on a where
clause with Eloquent ORM?
For example, I want to find a specific Product object that is related to a Store object. I thought I could do something like this:
$store = Store::where('hash', Input::get('s'))->first();
$product = $store->products->where('ext_id', 2)->get();
However, I'm getting an error that where
is an unknown method. If instead of where I use find
, that works correctly:
$product = $store->products->find(1);
Why can't I use where
this way?
Upvotes: 1
Views: 1483
Reputation: 81187
$product = $store
->products()
->where('ext_id', 2)->get();
This will not run 2 queries.
The difference is this:
$store->products() // relation object you can query
$store->products // already fetched related collection / model (depending on relation type)
Also you can use eager loading:
$store = Store::where('hash', Input::get('s'))
->with(['products' => function ($q) {
$q->where('ext_id', 2);
}])->first();
This will load only ext_id = 2
products on the store, that will be accessible via $store->products
Now, there are different methods find
involved:
$store->products()->find(1); // runs select ... where id=1
$store->products->find(1); // gets model with id 1 from the collection
Upvotes: 2