php – 在Laravel 5中创建一个嵌套的类别列表
发布时间:2020-12-14 19:39:15 所属栏目:大数据 来源:网络整理
导读:对Laravel来说相当新,我正在尝试为我的应用程序创建一个类似树的类别结构.这是我以前使用的代码,但仍然无法实现我想要的. 我的控制器: public function index(){ $categories = Category::with('children')-get(); return view('backend.categories.index')
对Laravel来说相当新,我正在尝试为我的应用程序创建一个类似树的类别结构.这是我以前使用的代码,但仍然无法实现我想要的.
我的控制器: public function index() { $categories = Category::with('children')->get(); return view('backend.categories.index')->with('categories',$categories); } 我的分类型号: <?php namespace App; use IlluminateDatabaseEloquentModel; class Category extends Model { protected $guarded = ['id']; public function parent() { return $this->belongsTo('AppCategory','parent_id'); } public function children() { return $this->hasMany('AppCategory','parent_id'); } } 我的看法: <table class="table table-bordered table-hover"> <thead> <tr> <th>Name</th> <th>Description</th> <th>Slug</th> <th>Action</th> </tr> </thead> <tbody> @foreach ($categories as $category) {{--@foreach ($category->children as $children)--}} <tr> <td>{{ $category->name }}</td> <td>{{ $category->description }}</td> <td>{{ $category->slug }}</td> <td><a class="edit" href="{!! action('AdminCategoriesController@edit',$category->id) !!}" title="Edit"><i class="fa fa-pencil-square-o"></a></i> <a class="delete" href="{!! action('AdminCategoriesController@destroy',$category->id) !!}" title="Are you sure you want to delete?"><i class="fa fa-trash-o"></i></a></td> @foreach ($category->children as $children) <tr> <td>{{ $children->name }}</td> <td>{{ $children->description }}</td> <td>{{ $children->slug }}</td> <td></td> </tr> @endforeach </tr> </tbody> {{--@endforeach--}} @endforeach </table> 我试图产生如下结构: >时尚配饰 >包包 >手机 >平板电脑 编辑 +-------------+------------------+------+-----+---------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+------------------+------+-----+---------------------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | name | varchar(255) | NO | | NULL | | | slug | varchar(255) | NO | | NULL | | | parent_id | int(11) | YES | | NULL | | | description | text | NO | | NULL | | | created_at | timestamp | NO | | 0000-00-00 00:00:00 | | | updated_at | timestamp | NO | | 0000-00-00 00:00:00 | | +-------------+------------------+------+-----+---------------------+----------------+ 解决方法
您当前正在加载所有类别(包括子类别),然后循环遍历它们.您只想加载根类别(没有父类别的类别).为此,请将控制器方法更改为仅加载parent_id为null的类别.
$categories = Category::whereNull('parent_id')->with('children')->get(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |