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
Eloquent column list by key with array as values?
提问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 keyBy
method:
您可以使用以下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/value
array, since Laravel 5.1
you can use pluck
. This way you can indicate which attributes you want to use as a value
and 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 Object
instead of an Array
as value then just remove the (Array)
.
如果你想得到一个Object
而不是一个Array
as 值,那么只需删除(Array)
.
Alternative:Using Eloquent
model (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();
});