2016-09-28 26 views
0

我使用下面的代碼從兩個相關表中獲取數據:如何優化Laravel中的代碼?

$arr = []; 
$objectModel = new ProductCategory(); 
$objectModel::$language = 2; 

$subcategories = $objectModel::with("translate", "parent")->get(); 

foreach($subcategories as $key => $item) { 
    $arr[$item->translate()->first()->objectId] = $item->translate()->first()->name; 
} 

array_unshift($arr, 'Select category'); 
return $arr; 

在結果這部分代碼我得到key => value陣列在刀片模板選擇列表中插入此。

但我希望擺脫一個循環:

foreach($subcategories as $key => $item) { 
    $arr[$item->translate()->first()->objectId] = $item->translate()->first()->name; 
} 

而且從要求得到清晰的集合。我該怎麼做?

回答

1

您可以使用Laravel Collectionshttps://laravel.com/docs/5.3/collections

$arr = ProductCategory::with("translate", "parent")->get() 
      ->mapWithKeys(function ($item, $key) { 
       return [$item->translate()->first()->objectId => $item->translate()->first()->name]; 
      }) 
      ->all(); 
+0

爲什麼要用'收集()'在這裏嗎?文檔中說:「雄辯查詢的結果總是作爲集合實例返回。」請參閱「創建集合」的提示。 – Doom5