php - 类别和子类别的集合?
问题描述
类别表
编号| 姓名 | parent_id --|-------------------- |------------ 1 | 服装 | 无效的 2 | 衬衫 | 1 3 | 运动衫 | 2 4 | 男士运动衫| 3 5 | 帽子 | 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 包括整个集合,最终结果有集合包括它自己。
任何想法?
解决方案
该指导有些奏效,但最后我使用了一个有用的包 [lazychaser / laravel-nestedset][1]
这使得使用类别和子类别变得更加容易
$categories = Category::with('descendants')->get()->toTree();
要不就
$categories = Category::with('descendants')->get()->toFlatTree();
你也可以把祖先而不是后代放在很容易
[1]:https ://github.com/lazychaser/laravel-nestedset
推荐阅读
- javascript - 鼓机 webapp,触摸手机不工作
- javascript - 在 formik initialValues 中传递空值
- angular - ckeditor4-angular :删除链接目标值
- javascript - 在codeigniter 4中使用时刻js作为日期时间戳
- cpu - Intel Xeon E5-2640 v4 CPU 的理论最大性能 (FLOPS),仅使用加法?
- swift - 在 vapor4 中返回合理的数据
- python - 在 100,000 多个唯一 URL 的数据帧上使用 aiohttp
- reactjs - 反应上下文不更新组件
- python - 将熊猫数据框导出到 postgresql 数据库时遇到问题
- java - 如果第一个写入器失败,CompositeItemWriter 会跳过第二个写入器