类别表
ID | parent_id | 姓名 |
1 | 0 | 人力资源 |
2 | 1 | 设置 |
3 | 2 | 部门 |
4 | 3 | 职位 |
我想得到这样:
Array
(
[0] => stdClass Object
(
[id] => 1
[parent_id] => 0
[name] => Human Resource
[created_at] => 0000-00-00 00:00:00
[updated_at] => 2016-03-08 05:43:09
[sub_category] => Array
(
[0] => stdClass Object
(
[id] => 4
[parent_id] => 1
[page_name] => Settings
[icon] =>
[created_at] => 2016-03-09 11:53:35
[updated_at] => 2016-03-08 05:52:34
)
)
)
)
注意:我想要一个动态/无限的子类别。无限制 子类别的级别。
我已经有这样的查询:
$categories = DB::table('category')->where('parent_id',0)->get();
foreach ($categories as $key => $value) {
$value->sub_category = DB::table('category')->where('parent_id',$value->id)->get();
}
但是我怎样才能使这个递归循环呢?因为我想有无限级别的子类别。
> Parent cat
> Parent cat
> sub cat
> second sub cat
> third sub cat
等等等等。
你可以
使用这个控制器
public function create()
{
$categories = Category::all();
return view('backend.categories.create')->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)
<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
</table>
然后让孩子循环有条件,如果它已经运行了循环
你可以
使用它。
public function view() {
$categories = Category::with('children')->get();
return compact('categories'); // or use json_encode
}