原文地址: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文件中: @foreach($categories作为$category)number 类别名称 类别ID 类别描述 创建时间 状态 操作 {{$category->id}} {{$category->title}} {{$类别->created_at}} {{$child_category->id}} |{{str_repeat('--',$child_category->level-1)}}{{$child_category->title}} {{$child_category->created_at}} 复制代码tr>
