我有一个资源集合来获取我所有的对话。因为前端已经编码(由另一个人),所以我想将所有这些作为对象返回,以数据库的Dialogue_id作为键,以对话对象作为值。
但是当我想转换从资源集合中获取的数组(使用 (object) $array )时,它仍然返回一个没有我设置的任何键的数组。
在我的控制器函数中我调用:
return new DialogueResourceCollection($dialogues);
Run Code Online (Sandbox Code Playgroud)
我的收藏资源如下所示:
class DialogueResourceCollection extends ResourceCollection
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
$array = [];
for ($i = 0; $i < sizeof($this); $i++) {
$j = $this[$i]->dialogue_id;
$array[$j] = $this[$i];
}
return $array;
}
}
Run Code Online (Sandbox Code Playgroud)
我得到什么:
[
{
"dialogue_id": 1,
"text": "example text"
},
...
Run Code Online (Sandbox Code Playgroud)
我想得到什么:
{
"34" : {
"dialogue_id": 34,
"text": "example text"
},
...
}
Run Code Online (Sandbox Code Playgroud)
小智 11
当从路由返回资源集合时,Laravel 会重置集合的键,以便它们采用简单的数字顺序。但是,您可以将preserveKeys属性添加到资源类中,指示是否应保留集合键。将其放在您的代码之上。
public $preserveKeys = true;
Run Code Online (Sandbox Code Playgroud)
在这里阅读文档保留密钥
| 归档时间: |
|
| 查看次数: |
2621 次 |
| 最近记录: |