2 回答

TA貢獻1801條經驗 獲得超16個贊
該指南有些有效,但最后我使用了一個有用的包 [lazychaser / laravel-nestedset][1]
這使得使用類別和子類別變得更加容易
$categories = Category::with('descendants')->get()->toTree();
要不就
$categories = Category::with('descendants')->get()->toFlatTree();
你也可以用祖先代替后代 就這么簡單
[1]:https://github.com/lazychaser/laravel-nestedset

TA貢獻1809條經驗 獲得超8個贊
我建議將邏輯轉移到相關類中,以便更容易理解您在做什么。
控制器:
public function get(Category $category): Collection
{
return (new GetAllCategories($category))->handle();
}
模型
public function children(): HasMany
{
return $this->hasMany(Category::class, 'parent_id', 'id');
}
GetAllCategories 操作類。這個類將循環遍歷每個孩子并返回相關的孩子。
public function handle(): Collection
{
return $this->buildCategory($this->category);
}
protected function buildCategory(Category $category): Collection
{
return collect([
'category' => $category,
'children' => $this->getChildren($category),
]);
}
protected function getChildren(Category $category): Collection
{
return $category
->children
->map(fn($child) => $this->buildCategory($child));
}
我沒有添加use語句、__consturct方法或路由綁定。我假設您使用的是 php7.4 和 laravel 7.*
- 2 回答
- 0 關注
- 180 瀏覽
添加回答
舉報