重命名 Laravel 集合“数据”键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44907226/
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
Rename laravel collection "data" key
提问by Cengkuru Michael
Is there way i can rename the data key in laravel collection results? At the moment this
有没有办法重命名laravel收集结果中的数据键?目前这
DB::table('contracts AS C')->paginate(1)
returns
回报
{
"current_page": 1,
"data": [
{
"id": 191,
"buyer": "John",
"provider": "Jane"
}
],
"from": 1,
"last_page": 1,
"next_page_url": "",
"path": "",
"per_page": 1,
"prev_page_url": null,
"to": 1,
"total": 1
}
What i would like is this
我想要的是这个
{
"current_page": 1,
"parties": [
{
"id": 191,
"buyer": "John",
"provider": "Jane"
}
],
"from": 1,
"last_page": 1,
"next_page_url": "",
"path": "",
"per_page": 1,
"prev_page_url": null,
"to": 1,
"total": 1
}
The challenge here changing the data key to parties
将数据密钥更改为各方的挑战
回答by linktoahref
回答by Robert
The data
key is only set when the Paginator object toArray()
is called. Before that it's a Collection with the key items
.
该data
键仅在toArray()
调用分页器对象时设置。在此之前,它是一个带有键的 Collection items
。
Quick and dirty solution would be to call toArray()
on the Paginator object and change the key name of the array before the json_encode()
.
快速而肮脏的解决方案是调用toArray()
Paginator 对象并在json_encode()
.
Another solution would be to extend the Builder class, much like it's done here, overwrite the paginate()
method and Paginator's toArray()
method.
另一种解决方案是扩展 Builder 类,就像这里所做的那样,覆盖该paginate()
方法和分页器的toArray()
方法。
回答by Mirko
You could just convert the collection to array and manipulate it:
您可以将集合转换为数组并对其进行操作:
$result = DB::table('contracts AS C')->paginate(1)->toArray();
$data = $result['data'];
unset($result['data']);
$result['parties'] = $data;
return $result;
This does not require any extra loops either.
这也不需要任何额外的循环。