类别表
id| name | parent_id
--|------------------ |-----------
1 | Clothing | null
2 | Shirt | 1
3 | Sports shirt | 2
4 | Men's sports shirt | 3
5 | Hat | 1
类别型号:
public function child()
{
return $this->hasMany(Category::class, 'parent_id', 'id');
}
public function newRelation($allCategories){
if ($this->child->isNotEmpty()) {
$children = collect();
$allCategories = $this->subCategories($children);
}
return $allCategories->unique();
}
public function subCategories($allCategories) {
$this->child->map(function($item, $key) use(&$allCategories){
$allCategories->push($item);
if ($item->child->isNotEmpty()) {
$allCategories->push($item->subCategories($allCategories));
}
});
return $allCategories;
}
控制器:
$allCategories = collect();
$category = Category::find(1);
$result = $category->newRelation($allCategories);
它是如何工作的,但在另一个集合中返回一些额外的数据集合,实际上在 subCategories 方法中每次返回 $allCategories 包括整个集合,最终结果有包含其本身的集合。
有什么想法吗?
侃侃尔雅
海绵宝宝撒