【发布时间】:2020-02-12 06:34:06
【问题描述】:
所以我一直试图从我的“CategoryResource”中获得二级关系,但它不起作用,这是我的一些代码:
首先,我的模型:
public function children()
{
return $this->hasMany(Category::class, 'parent_id', 'id');
}
public function sub_children()
{
return $this->hasMany(Category::class, 'parent_id');
}
然后是“CategoryResource”:
$data = [
'id' => $this->id,
'parent_id' => $this->parent_id,
'order' => $this->order,
'name' => $this->name,
'slug' => $this->slug,
'childs' => CategoryResource::collection($this->whenLoaded('children') && $this->whenLoaded('children')),
'created_at' => (string) $this->created_at,
'updated_at' => (string) $this->updated_at,
];
我的控制器
return CategoryResource::collection(Category::where('parent_id',null)->with('children.sub_children')->get());
无论如何我可以通过 laravel 资源检索我的嵌套关系吗?
【问题讨论】: