Laravel Eloquent:带有对象值的getDictionary作为结果的值

时间:2016-05-25 00:04:09

标签: laravel eloquent laravel-5.2

目前,$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"

我试过了:

  • keyBy
  • 列表
  • getDictionary
  • 地图

2 个答案:

答案 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方法。