2016-05-25 41 views
1

目前,$mymodel->getDictionary();回報:Laravel雄辯:getDictionary與對象的值作爲結果的值

this

我所尋找的是這樣的:

"7gct5YaTvuxBmY2" => "Leadership", 
"7NrXZepqczMSHqM" => "...", 
"..." => "...", 
... 

我成功的唯一途徑這是:

$construct_obj = OrganizationalConstruct::where('is_root', 0)->where('organization_id', $this->current_company->company_id)->get(); 
$constructs = []; 
$constructs[''] = ''; 
for ($i = 0; $i < count($construct_obj); $i++) { 
    $constructs[$construct_obj[$i]->organizational_construct_id] = $construct_obj[$i]->construct_name; 
} 

是否有一個ea更方便獲得格式"key" => "speific-column-value"

我曾嘗試:

  • keyBy
  • 名單
  • getDictionary
  • 地圖

回答

2

您應該直接調用pluck上查詢,這樣你就不會爲所有機型拉下所有屬性:

$dictionary = OrganizationalConstruct::where('is_root', 0) 
        ->where('organization_id', $this->current_company->company_id) 
        ->pluck('construct_name', 'organizational_construct_id'); 

注:lists已被棄用,並將在Laravel 5.3被刪除。改用pluck方法。

+0

謝謝!奇蹟般有效 – Haring10

2

一個非常簡單的答案其實。它看起來像lists方法可以接受多個參數,允許我通過id作爲參數1和name作爲參數2給我在一行中所需的結果key => value

所以這個:

$construct_obj = OrganizationalConstruct::where('is_root', 0)->where('organization_id', $this->current_company->company_id)->get(); 
$constructs = []; 
$constructs[''] = ''; 
for ($i = 0; $i < count($construct_obj); $i++) { 
    $constructs[$construct_obj[$i]->organizational_construct_id] = $construct_obj[$i]->construct_name; 
} 

變成這樣:

$construct_obj = OrganizationalConstruct::where('is_root', 0)->where('organization_id', $this->current_company->company_id)->get(); 
$construct_obj->lists('construct_name', 'organizational_construct_id'); 

希望這可以幫助其他人。

+0

顯然'列表'方法將在Laravel 5.3中刪除,所以請使用'pluck'方法。由於這個原因,約瑟夫的答案被標記爲正確。 – Haring10