目前,$mymodel->getDictionary();
返回:
https://riot-controls.herokuapp.com/
我正在寻找的是:
"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;
}
是否有更简单的方法来获取格式"key" => "speific-column-value"
?
我试过了:
答案 0 :(得分:2)
实际上是一个简单的答案。看起来lists
方法可以接受多于1个参数,允许我将id
作为参数1和name
作为参数2传递给我{{1}所需的结果在一行。
所以这个:
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;
}
希望这有助于其他人。
答案 1 :(得分: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
方法。