【发布时间】:2020-08-03 16:55:16
【问题描述】:
我有一个多级类别模型,每个类别可以在同一个 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 |
+---------+---------+------------+
我想从我的控制器中获取所有类别及其主类别(不是父类别),如下所示:
$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
我需要一个模型函数,它为每个类别返回类别和 mainCategory,因此我可以从另一个控制器而不是 CategoryController 应用该函数。
【问题讨论】:
-
为父类和子类创建两个表,你可以轻松使用hasMany
-
感谢您的回复,但我认为您没有很好地回答问题。
标签: laravel nested treeview parent-child eloquent-relationship