当前位置: 首页 > 后端技术 > PHP

Laravel5.4实现无限分类

时间:2023-03-30 02:16:16 PHP

1、构建phpartisanmake:migrationcreate_category_table--create=category在database/migrations/下找到你的迁移文件构建:increments('id');$table->integer('parent_id');$table->string('code');$table->string('name');$table->string('path');$table->timestamps();});}/***反转迁移。**@returnvoid*/publicfunctiondown(){Schema::dropIfExists('categorys');}}phpartisanmigrate2、建模型在app/Category.phpphpartisanmake:modelCategory-mhasMany('App\Category','parent_id','id');}publicfunctionallChildrenCategorys(){return$this->childCategory()->with('allChildrenCategorys');}}3.调用$categorys=App/Category::with('allChildrenCategorys')->first();或$categorys->allChildrenCategorys;或者$categorys->allChildrenCategorys->first()->allChildrenCategorys;将树分类转换成数组ID有朋友问这个问题,我这里更新了$arr=[];array_walk_recursive($categories,function($v,$k)use(&$arr){if($k=='id')$arr[]=$v;});