问题描述
对于Laravel来说还很陌生,他正在尝试为我的应用程序创建一个类似树的类别结构.这是我以前使用过的代码,但仍然无法实现我想要的功能.我的控制器:
Am fairly new to Laravel and am trying to create a tree-like categories structure for my app. This is the code have I used to far but still unable to achieve what I want.My controller:
public function index()
{
$categories = Category::with('children')->get();
return view('backend.categories.index')->with('categories', $categories);
}
我的类别模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $guarded = ['id'];
public function parent()
{
return $this->belongsTo('App\Category', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Category', '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('Admin\CategoriesController@edit', $category->id) !!}" title="Edit"><i class="fa fa-pencil-square-o"></a></i> <a class="delete" href="{!! action('Admin\CategoriesController@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>
我正在尝试生成如下结构:
Am trying to produce a structure like below:
- 时尚配饰
- 包包
- 衣服
- Fashion Accessories
- Bags
- Cloths
- 平板电脑
- 智能手机
编辑有我的数据库结构:
EDITThere is my database structure:
+-------------+------------------+------+-----+---------------------+----------------+ | 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
的类别.You are currently loading all categories (including the child ones) and then looping through them. You only want to load the root categories (categories without parent). To do this, change your controller method to only load categories where the
parent_id
isnull
.$categories = Category::whereNull('parent_id')->with('children')->get();
这篇关于在Laravel 5中创建类别的嵌套列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!