如何在 Laravel 5.7 中返回集合的子集合?我有一個(gè) Laravel 集合,它本身包含一個(gè)集合。當(dāng)我通過我的 api 返回父集合時(shí),顯然有一個(gè)“子”對(duì)象,但是當(dāng)我嘗試返回“子”對(duì)象時(shí)它為空。相關(guān)收藏代碼:$item = [ 'id' => $this->id, ... $this->mergeWhen($this->type === Item::[type], [ ... 'children' => [type]::collection($this->[prop]) ]),...return $item;];相關(guān)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], ... } ]}但是當(dāng)我把它改成$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
1 回答

慕后森
TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
嘗試這個(gè) :
...
$return_array = collect();
foreach ($items as $item)
{
$return_array->push($item->children);
}
return $return_array->toArray();
- 1 回答
- 0 關(guān)注
- 156 瀏覽
添加回答
舉報(bào)
0/150
提交
取消