4 回答
TA贡献1820条经验 获得超9个赞
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贡献2039条经验 获得超7个赞
这就是我如何让它工作:
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贡献1859条经验 获得超6个赞
我正在使用这种结构
您的输入类别模型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选择2
- 4 回答
- 0 关注
- 163 浏览
添加回答
举报