我被困在树状结构菜单中。
这是我的表
+----+----------------------+----------------------+-----------+
| 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('App\Category', 'parent_id');}
public function children(){
return $this->hasMany('App\Category', 'parent_id');}
通缉输出:
- Cameras
- Lighting
-- Portable Lights
--Lighting Accessories
-- Studio Lights
- Lens
-- Tripods
- Accessories
- Miscellaneous
我希望将上述结果放在包含(id
和title
)的数组中。
答案 0 :(得分:0)
在模型中创建关系,如
public function children() {
return $this->hasMany('App\Category','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'));
}
答案 1 :(得分:0)
你应该尝试以下解决方案。
放置您的模型文件。
public function children() {
return $this->hasMany('App\Category','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 数组中获取所有子项和子项数据。
答案 2 :(得分:0)
好的,所以Collection管道非常适合您想要做的事情。到此为止;
// 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
相同,依此类推。