[英]Laravel Eloquent ORM find related object
What is the correct way to find a related object based on a where
clause with Eloquent ORM? 用Eloquent ORM基于
where
子句查找相关对象的正确方法是什么?
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. 但是,我收到一个错误,指出
where
是未知方法。 If instead of where I use find
, that works correctly: 如果不是我在哪里使用
find
,那可以正常工作:
$product = $store->products->find(1);
Why can't I use where
this way? 为什么我不能
where
这种where
使用?
$product = $store
->products()
->where('ext_id', 2)->get();
This will not run 2 queries. 这将不会运行2个查询。
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
这只会在商店中加载
ext_id = 2
产品,可以通过$store->products
Now, there are different methods find
involved: 现在,
find
不同的方法:
$store->products()->find(1); // runs select ... where id=1
$store->products->find(1); // gets model with id 1 from the collection
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.