我被困在树结构菜单中。
这是我的桌子
+----+----------------------+----------------------+-----------+
| id | title | slug | parent_id |
+----+----------------------+----------------------+-----------+
| 1 | Cameras | cameras | 0 |
| 2 | Lighting | lighting | 0 |
| 3 | Portable Lights | portable-lights | 2 |
| 4 | Studio Lights | studio-lights | 2 |
| 5 | Lighting Accessories | lighting-accessories | 3 |
| 6 | Lens | lens | 0 |
| 7 | Tripods | tripods | 6 |
| 8 | Accessories | accessories | 7 |
| 9 | Miscellaneous | miscellaneous | 7 |
+----+----------------------+----------------------+-----------+
这是我的关系
public function parent(){
return $this->belongsTo('AppCategory', 'parent_id');}
public function children(){
return $this->hasMany('AppCategory', 'parent_id');}
想要输出:
- Cameras
- Lighting
-- Portable Lights
--Lighting Accessories
-- Studio Lights
- Lens
-- Tripods
- Accessories
- Miscellaneous
我希望上述结果具有(id
和title
(。
好吧,因此收集管道非常适合您想做的事情。这里;
// Retrieve all categories and then key them by their id
$categories = Category::all()->keyBy('id');
$categories->filter(function (Category $category) {
// We want to only grab the categories that are children
return $category->parent_id;
})->each(function (Category $category) use($categories) {
// We not want to get the parent of this category
$parent = $categories->get($category->parent_id);
if ($parent) {
// If the parent exists, and we haven't seen it yet, set a default collection
if (! $parent->relationLoaded('children')) {
$parent->setRelation('children', new Collection);
}
// We can be confident that it's a collection and won't auto load, so we add
$parent->children->push($category);
}
});
// Finally we want to return only root categories
return $categories->filter(function (Category $category) {
return ! $category->parent_id;
});
我已经在代码中发表了评论,希望可以解释发生了什么。我没有测试过此代码,但应该起作用。
该集合应具有三个条目Cameras
,Lighting
和Lens
。Lighting->children
应该有2个条目,Portable Lights->children
具有1. Lens->children
等。
在
之类的模型中创建关系 public function children() {
return $this->hasMany('AppCategory','parent_id','id') ;
}
之后,您的控制器动作获得类别结果,例如
public function getCategoryList()
{
$categories = Category::where('parent_id', '=', 0)->get();
$allCategories = Category::pluck('title','id')->all();
return view('categoryTreeMenu',compact('categories','allCategories'));
}
您将在下面的解决方案下尝试。
放置模型文件。
public function children() {
return $this->hasMany('AppCategory','parent_id','id') ;
}
您的控制器文件。
$parent = Task::where('parent_id', '=', 0)->get();
foreach($parent as $key => $value){
if(isset($value->children)){
$parent[$key]['children'] = $value->children;
foreach ($parent[$key]['children'] as $key1 => $value1) {
if(isset($value1->children)){
}
}
}
}
您可以在 $ parent array中获取所有子女数据。