2013-08-26 64 views
1

我試圖讓表嵌套繼承並篩選某些列。無法找到容易做到的事情。Laravel Eloquent從嵌套表中獲取某些列使用()

我有錶店女巫有許多地方(和位置都有一個城市)和許多行動

我想這一切在一次與口才,對特定的列過濾器。

這是我過濾商店表,但不知道如何過濾表位置和操作。

$this->shop->with('locations')->with('actions')->get(array('id','name','recommended','category_id')); 

我需要的是這樣的:

$this->shop 
->with('locations',Location::with('city', City::get(array('id','name')))->get(array('id','name'))) 
->with('actions', Action::get(array('id','name')))->get(array('id','name'));); 

回答

0

Laravel Eloquent: How to get only certain columns from joined tables

這樣做是爲了過濾模型中的列(如上面的鏈接頂端回答說)最簡單的方法。但是,如果要構建動態查詢,這可能會很不方便。

從理論上講,你應該能夠做到:

$this->shop->with(array('locations' => function($query) { 
              $query->select('id', '...etc...'); 
             } 

...不幸的是它似乎並不爲選擇工作();當我測試它時,我得到一個空白數組。其他方法可以工作,但是,例如,

$this->shop->with(array('locations' => function($query) { 
              $query->orderBy('id', 'DESC'); 
             } 

使用Fluent查詢生成器可能會更好。它不像ORM那樣「性感」或流行,但我發現在處理動態查詢時更易於使用。

+0

以及我試圖與查詢builde連接表,但它不工作。 $ stores = DB :: table('shops') - > join('locations','locations.shop_id','=','shops.id') - > join('actions','actions.shop_id ','=','shops.id') - > select('shops.id','locations.id','actions.id'); – zajca

+0

你如何鏈接多個這些?我嘗試向數組中添加另一個函數,但它失敗了。謝謝 – Notflip

相關問題