繁体   English   中英

我如何处理作为 Laravel 5.7 中集合的子集合的集合?

[英]How do I work with a collection that is a child of a collection in Laravel 5.7?

如何在 Laravel 5.7 中返回集合的子集合? 我有一个 Laravel 集合,它本身包含一个集合。 当我通过 api 返回父集合时,显然有一个“子”对象,但是当我尝试返回“子”对象时,它为空。

相关采集代码:

$item =  [
  'id' => $this->id,
  ...
  $this->mergeWhen($this->type === Item::[type], [
     ...
     'children' => [type]::collection($this->[prop])
  ]),
...
return $item;
];

相关api控制器代码:

$itemsQuery = $[parent_type]->items()->topLevel()->withAll()->ordered()->get();
$items = [type]::collection($itemsQuery);

$return_array = [];

foreach ($items as $item)
{         
  array_push($return_array, $item);  
}    

return $return_array;

这将返回我所期望的。

"data": {
    "id": [guid],
    ...
    "children": [
     {
       "id": [guid],
       ...
     }
  ]
}

但是当我把它改成

$itemsQuery = $[parent_type]->items()->topLevel()->withAll()->ordered()->get();
$items = [type]::collection($itemsQuery);

$return_array = [];

foreach ($items as $item)
{         
  array_push($return_array, $item->children);  
}    

return $return_array;

我得到

"data": null

尝试这个 :

...

$return_array = collect();

foreach ($items as $item)
{         
  $return_array->push($item->children); 
}    

return $return_array->toArray();

有一个collect()助手,不确定它是否会帮助您,但是您可以通过这种方式将基本数组转换为集合。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM