2014-08-27 64 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