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

Laravel的无限分类实现方法

时间:2023-03-29 15:50:55 PHP

原文地址:https://www.wjcms.net/archive...网上的资料和文档很多,要么不详尽,要么根本不对,要么达不到预期的目的。其实思路和实现方法都很简单。今天就让我们一起体会吧。这里创建模型控制器数据迁移文件直接使用artisan命令创建#-a其实就是全部,创建模型,控制器(资源),数据迁移文件(工厂模型,种子)phpartisanmake:model-aCategoryrunthis创建资源控制器的命令。修改数据迁移文件,首先修改数据迁移文件xxx_create_categories_table。打开文件,修改里面的up方法,添加相应的字段。Schema::create('categories',function(Blueprint$table){$table->id();$table->string('title',100)->comment('categoryname');$table->string('name',100)->comment('类别标识');$table->string('description',255)->nullable()->comment('类别描述');$table->integer('pid')->default(0)->comment('categoryid');$table->integer('level')->default(1)->comment('categorylevel');$table->integer('sort')->default(0)->comment('sort');$table->integer('status')->default(1)->comment('status:0-disabled,1-正常');$table->timestamps();});执行迁移命令phpartisanmigratenestedmodelimplementationread//App\Models\Category.phppublicfunctioncategories(){return$this->hasMany(self::class,'pid','id')->with('类别');}控制器调用//app\Http\controllers\CategooryController.php#usemodeluseApp\Models\Category;publicfunctionindex(){$类别=Ccategory::with('categories')->where('pid',0)->get();返回视图('category.index',紧凑('categories'));在routes/web中添加路由。在php中,我们添加以下内容:Route::get('category','CategoryController@index');blade模板渲染这里使用递归渲染在resources/views/categories.blade.php文件中:number类别名称类别ID类别描述创建时间状态操作@foreach($categories作为$category){{$category->id}}{{$category->title}}{{$category->name}}{{$category->描述}}{{$类别->created_at}}{{$category->status}}@foreach($category->categories作为$childCategory)@include('category.child_category',['child_category'=>$childCategory])@endforeach@endforeach发送部分加载自我模型版child_category.blade.php{{$child_category->id}}|{{str_repeat('--',$child_category->level-1)}}{{$child_category->title}}{{$child_category->name}}{{$child_category->描述}}{{$child_category->created_at}}{{$child_category->status}}@if($child_category->categories)@foreach($child_category->categoriesas$childCategory)@include('category.child_category',['child_category'=>$childCategory])@endforeach@endif最后看一下效果