php Eloquent 列以数组为值按键列出?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24130507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:10:08  来源:igfitidea点击:

Eloquent column list by key with array as values?

phplaravellaravel-4eloquent

提问by eComEvo

So I can do this with Eloquent:

所以我可以用 Eloquent 做到这一点:

$roles = DB::table('roles')->lists('title', 'name');

But is there a way to make Eloquent fetch an array of values for each distinct key instead of just one column?

但是有没有办法让 Eloquent 为每个不同的键获取一组值,而不仅仅是一列?

For instance, something like the following:

例如,类似于以下内容:

$roles = DB::table('roles')->lists(['*', DB:raw('COALESCE(value, default_value)')], 'name');

回答by Joseph Silber

You can use the keyBymethod:

您可以使用以下keyBy方法:

$roles = Role::all()->keyBy('name');


If you're not using Eloquent, you can create a collection on your own:

如果你不使用 Eloquent,你可以自己创建一个集合:

$roles = collect(DB::table('roles')->get())->keyBy('name');


If you're using Laravel 5.3+, the query builder now actually returns a collection, so there's no need to manually wrap it in a collection again:

如果您使用的是 Laravel 5.3+,查询构建器现在实际上会返回一个集合,因此无需再次手动将其包装在集合中:

$roles = DB::table('roles')->get()->keyBy('name');

回答by tomloprod

If you need a key/valuearray, since Laravel 5.1you can use pluck. This way you can indicate which attributes you want to use as a valueand as a key.

如果你需要一个key/value数组,因为Laravel 5.1你可以使用pluck. 通过这种方式,您可以指明要用作 avalue和 a 的属性key

$plucked = MyModel::all()->pluck('MyNameAttribute', 'MyIDAttribute');

return $plucked->all();

You will get an array as follow:

你会得到一个数组,如下所示:

array:3 [▼
   1 => "My MyNameAttribute value"
   2 => "Lalalala"
   3 => "Oh!"
]

回答by The Alpha

You may try something like this:

你可以尝试这样的事情:

$roles = array();
array_map(function($item) use (&$roles) {
    $roles[$item->id] = (Array)$item; // object to array
}, DB::table('roles')->get());

If you want to get an Objectinstead of an Arrayas value then just remove the (Array).

如果你想得到一个Object而不是一个Arrayas 值,那么只需删除(Array).

Alternative:Using Eloquentmodel (Instead of DB::table):

替代方案:使用Eloquent模型(而不是DB::table):

$roles = array();
array_map(function($item) use (&$roles) {
    $roles[$item['id']] = $item;
}, Role::all()->toArray());

Another Alternative:Using Collection::map()method:

另一种选择:使用Collection::map()方法:

$roles = array();
Role::all()->map(function($item) use(&$roles) {
    $roles[$item->id] = $item->toArray();
});