laravel 无限级分类

原文:https://segmentfault.com/a/1190000010359094(感谢作者给的思路和想法,但是按文章实践踩了不少坑,所以这边认真写个笔记对像我这样的萌新能友好一点)


目的:获取父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了

image

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.结果及解释 image 因为表里对于id=5的只有一个id=6的儿砸和id=7的孙砸

再次感谢大佬的文章~

变数组加个->toArray()就好了

array:1 [▼
  0 => array:8 [▼
    "id" => 6
    "parent_id" => 5
    "code" => "6"
    "name" => "6"
    "path" => "6"
    "created_at" => "2018-07-06 10:35:16"
    "updated_at" => "2018-07-06 10:35:18"
    "all_children_categorys" => array:1 [▼
      0 => array:8 [▼
        "id" => 7
        "parent_id" => 6
        "code" => "7"
        "name" => "7"
        "path" => "7"
        "created_at" => "2018-07-19 10:53:55"
        "updated_at" => "2018-07-25 10:54:00"
        "all_children_categorys" => []
      ]
    ]
  ]
]
最后修改:2019-11-17 21:41:21
0