2014-08-27 120 views
1

根据带有Eloquent ORM的where子句找到相关对象的正确方法是什么?Laravel Eloquent ORM查找相关对象

例如,我想查找与Store对象相关的特定Product对象。我想我可以做这样的事情:

$store = Store::where('hash', Input::get('s'))->first(); 
$product = $store->products->where('ext_id', 2)->get(); 

但是,我得到一个错误,where是一个未知的方法。相反,如果在那里我用find,即正常工作:

$product = $store->products->find(1); 

为什么我不能用where这样?

+0

你不能使用where在这个场合,但如果你做$ store->产品() - >在哪里( 'EXT_ID',2) - > get()方法,这应该工作。 ()允许你再次查询。这是因为$ store-> products是一个集合。 – 2014-08-27 15:13:06

+0

但是,这是否会运行其他查询?因此,$ store-> products()运行查询以选择与商店相关的所有产品,然后 - > get()再次运行查询以选择与商店相关的所有产品,其中ext_id = 2?看来第一个查询是完全不必要的,不是吗? – flyingL123 2014-08-27 15:22:02

+0

是的,基于DB :: getQueryLog()的输出,它看起来像是在运行2个查询。第一个似乎无关紧要。必须有更好的方法来实现这一点。 – flyingL123 2014-08-27 16:30:09

回答

1
$product = $store 
    ->products() 
    ->where('ext_id', 2)->get(); 

这将跑2个查询。

的区别是:

$store->products() // relation object you can query 
$store->products // already fetched related collection/model (depending on relation type) 

您也可以使用预先加载:

$store = Store::where('hash', Input::get('s')) 
    ->with(['products' => function ($q) { 
     $q->where('ext_id', 2); 
    }])->first(); 

这将只加载ext_id = 2产品的专卖店,这将是访问通过$store->products


现在,有不同的方法find涉及:

$store->products()->find(1); // runs select ... where id=1 
$store->products->find(1); // gets model with id 1 from the collection