[英]Laravel rename collection keys
I have the following line to get an array of collections.我有以下行来获取 collections 的数组。
$tags = Tag::all()->map->only(['id', 'name']);
Which produces the following data.这会产生以下数据。
[{"id":1,"name":"tag 2"},{"id":2,"name":"tag 3"},{"id":3,"name":"tag-44"},{"id":4,"name":"biyoloji"}]
My objective is to rename the key names inside the collections as follows.我的目标是重命名 collections 中的键名,如下所示。
[{"value":1,"text":"tag 2"},{"value":2,"text":"tag 3"},{"value":3,"text":"tag-44"},{"value":4,"text":"biyoloji"}]
Basically, I want to rename "key" to "value" and "name" to "text."基本上,我想将“key”重命名为“value”,将“name”重命名为“text”。 I tried the
pluck()
function, get()
function, mapping but couldn't get it to work.我尝试了 pluck
pluck()
function, get()
function,映射但无法正常工作。 Most probably, iterating over it with foreach and toArray()
would do the trick, but I'm looking for the proper way to do it.最有可能的是,使用 foreach 和
toArray()
对其进行迭代可以解决问题,但我正在寻找正确的方法来做到这一点。 My environment is Laravel 8 with PHP 7.4我的环境是 Laravel 8 和 PHP 7.4
You can do this via your query more efficiently您可以通过查询更有效地做到这一点
$tags = Tag::get(['id as value', 'name as text']);
The best way I can propose:我可以提出的最佳方式:
$tags = Tag::query()->get(['id', 'name'])
->map(function($tag){
return [
'value' => $tag->id,
'text' => $tag->name,
];
})
->toArray();
Pay attention to get(['id', 'name])
invoking.注意
get(['id', 'name])
调用。 Passing required fields to get
method helps improving query performance.将必填字段传递给
get
方法有助于提高查询性能。 Specially if there are lots of unused columns in the table.特别是如果表中有很多未使用的列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.