Laravel 无限级分类的简单实践
原文:https://segmentfault.com/a/119000001035909...(感谢作者给的思路和想法,但是按文章实践踩了不少坑,所以这边认真写个笔记对像我这样的萌新能友好一点)
目的:获取父id的全部后代(包括儿砸,孙砸...)
准备:
- 一个数据表categories;
- 一个category的model
实践:
1.创建模型文件,并用-m创建迁移文件
php artisan make:model Models/Category -m
2.修改database下的category迁移文件
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->integer('parent_id');
$table->string('code');
$table->string('name');
$table->string('path');
$table->timestamps();
});
3.运行迁移命令,生成数据表category
php artisan migrate
4.往表里随意填充测试数据,这边测试,就不用factory了
5.修改Category.php文件,增加下面俩方法
public function childCategory() {
return $this->hasMany('App\Models\Category', 'parent_id', 'id');
}
public function allChildrenCategorys()
{
return $this->childCategory()->with('allChildrenCategorys');
}
6.建立路由及控制器 测试
//无限极分类测试
public function index(){
$category = Category::with('allChildrenCategorys')->find(5);
$re = $category->allChildrenCategorys;
dd($re);
}
//find一个parent_id = 0就可以
7.结果及解释
因为表里对于id=5的只有一个id=6的儿砸和id=7的孙砸
再次感谢大佬@sethhu的文章~
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: