php - Laravel 资源 - 有孩子的父母类别
问题描述
我想使用 Laravel 资源在父级中加载我的子级类别。
我的json是这样的:
"data": [
{
"id": 2,
"slug": "child-categorie-0",
"name": "Child Catégorie 0",
"parent_id": 1
},
{
"id": 3,
"slug": "child-categorie-1",
"name": "Child Catégorie 1",
"parent_id": 1
},
{
"id": 1,
"slug": "parent-categorie-0",
"name": "Parent Catégorie 0",
"parent_id": null
},
],
我想成为那样:
"data": [
{
"id": 1,
"slug": "parent-categorie-0",
"name": "Parent Catégorie 0",
"childrens": [
{
"id": 2,
"slug": "child-categorie-0",
"name": "Child Catégorie 0",
},
{
"id": 3,
"slug": "child-categorie-1",
"name": "Child Catégorie 1",
}
]
}
],
应用\Http\Resources\Category.php
public function toArray($request)
{
return [
'id' => $this->id,
'slug' => $this->slug,
'name' => $this->name,
'parent_id' => $this->parent_id
];
}
控制器
$categories = Category::orderBy('name', 'asc')->get();
return new CategoryCollection($categories);
我是 Laravel 资源的新手,所以如果有人有解决这个问题的方法,谢谢!
解决方案
我解决了我的问题!
我在我的类别模型中创建了一个关系。
public function childrens()
{
return $this->hasMany('App\Category', 'parent_id', 'id');
}
在我的类别资源中
public function toArray($request)
{
return [
'slug' => $this->slug,
'name' => $this->name,
'childrens' => self::collection($this->whenLoaded('childrens'))
];
}
在我的控制器中
$categories = Category::with('childrens')->parents()->orderBy('name','asc')->get();
推荐阅读
- logrotate - 为什么我的 logrotation 在 linux 中不能正常运行?
- c++ - 我需要为学校项目找出简单的循环
- python-3.x - 我不明白 python Dash @Callback 如何知道执行 def 函数
- mysql - mysql select view_definition 返回多个定义
- dependencies - 在 Nestjs 中,如果服务中未提及 Injectable 但服务在每个模块中注册为提供者,那么 DI 将如何工作
- javascript - 将变量传递给 setTimeout()
- javascript - Firebase signInWithGoogle() 要我填写电子邮件和密码字段吗?
- azure-devops - 对多个应用程序使用单个管道
- sql-server - 访问权限 sp_configure 和 reconfigure 语句?
- google-apps-script - 在 Apps 脚本中为公司范围的插件配置可安装触发器