[英]Laravel : Get main level category on a tree parent child relationship
我有一个多级类别 model,每个类别可以在同一个 sql 表的同一个表(树结构)上有子项和父项。
public function childs(){
return $this->hasMany('App\Category', 'parent_id', 'id');
}
public function parent(){
return $this->belongsTo('App\Category', 'parent_id');
}
+---------+---------+------------+
| id |cat_name | parent_id |
+---------+---------+------------+
| 1 | A | NULL |
| 2 | B | NULL |
| 3 | AA | 1 |
| 4 | BB | 2 |
| 5 | AAA | 4 |
+---------+---------+------------+
从我的 controller 我想获得所有类别及其主要类别(不是父类别),如下所示:
$categories= Category::with('mainCategory')->get();
期望的结果
id: 1
cat_name: A
parent_id:null
mainCategory:{}
id: 2
cat_name: B
parent_id:null
mainCategory:{}
id: 3
cat_name: AA
parent_id:1
mainCategory:{
id: 1
cat_name: A
parent_id:NULL
}
id: 4
cat_name: BB
parent_id:2
mainCategory:{
id: 2
cat_name: B
parent_id:NULL
}
id: 5
cat_name: AAA
parent_id:3
mainCategory:{
id: 1
cat_name: AAA
parent_id:NULL
}
例如:ID 为 5 的类别 AAA -> mainCat 是 A
我需要一个 model function 返回每个类别和 mainCategory,所以我可以从另一个 controller 而不是 CategoryController 应用 function。
我明白你的问题。
为父子创建两个表,因为父类别有很多子类别
示例表
表格父类别
id, name
表子类别
id, parent_category_id
并创建两个 model
ParentCategoryModel
public function childs(){ return $this->hasMany(ChildCategoryModel::class, 'parent_category_id', 'id'); }
ChildCategoryModel
public function parent(){ return $this->belongsTo(ParentCategoryModel::class,'parent_category_id')->withDefault(); }
在你的 controller 中,你可以像这样使用 eloquent categories=ChildCategoryModel::with('parent')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.