4 回答
TA贡献1860条经验 获得超8个赞
protected function getCategoriesTree()
{
$categories = Category::where('parent_id',0)->get();
if($categories->count())
{
foreach ($categories as $category)
{
$categories_tree[$category->id] = $this->getChildCategories($category);
}
}
return response()->json(['categories' => $categories_tree]);
}
private function getChildCategories($category)
{
$sub_categories = [];
$childs = Category::where('parent_id', $category->id)->get();
$sub_categories = $category;
$sub_categories['sub_categories'] = [];
if($childs->count())
{
$sub_categories['sub_categories'] = $childs;
}
return $sub_categories;
}
TA贡献1848条经验 获得超10个赞
这就是我让它工作的方式:
function getParentsTree($category, $name)
{
if ($category->parent_id == null)
{
return $name;
}
$parent = Category::find($category->parent_id);
$name = $parent->name . ' > ' . $name;
return getParentsTree($parent, $name);
}
$cat = Category::find(1);
echo getParentsTree($cat, $cat->name);
输出 :Electronics > Laptops > Accessories
TA贡献1842条经验 获得超12个赞
我正在使用这种结构
您的输入类别模型App\Category.php
class Categories extends Model
{
public function parent()
{
return $this->hasOne('App\Category', 'parent_id','id');
}
public function childiren()
{
return $this->hasMany('App\Category', 'id','parent_id');
}
}
你的控制器ExampleController.php
public function example()
{
$data = Category::all();
return view('index', compact('data'));
}
你的刀片index.blade.php
<select>
@foreach($data as $categories)
<optgroup label="{{ $categories->name }}">
@foreach($categories->children as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
@endforeach
</optgroup>
@endforeach
</select>
你也使用jquery select 2
- 4 回答
- 0 关注
- 111 浏览
添加回答
举报