laravel - 如何处理 laravel 资源中的嵌套关系 - 2
问题描述
所以我一直试图从我的“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 资源检索我的嵌套关系吗?
解决方案
您可以with
在关系中使用函数。它会是这样的:
public function children()
{
return $this->hasMany(Category::class, 'parent_id', 'id')
->with('children');
}
它将加载孩子,然后加载“subChildren”作为第一个对象的关系。
因此,您将其加载为:
$children = $originalObject->children;
foreach ($children as $c) {
$subChildren = $c->children;
}
检查这是否适用于您的问题。
推荐阅读
- database - 关系数据库设计(访问)
- node.js - 在不同的微服务中序列化多对多表
- android - 什么可以在 Android N+ 上加载私有原生库?
- excel - 如何基于模板创建电子邮件?
- javascript - Gravity Forms使用JS统计List中的行数并返回字段?
- mongodb - 为什么数据会保留在 mongo docker 容器中?
- react-native - 在现有视图组件中添加多个文本组件 - REACT NATIVE
- google-search - 我的结构化数据类型应该是 Product 还是 ItemPage?
- tmux - tmux 可以查询物理终端吗?(也许只有 iTerm2)
- c# - 如何单击列表框中的标签并在多个文本框中显示文本