[英]Laravel 5.6 Nested Categories
I am using Laravel 5.6.我正在使用 Laravel 5.6。 I am stuck with the following.
我坚持以下。 The structure of my category model is below.
我的类别模型的结构如下。
id | name | cat_parent_id | slug
--- | ------------------| ------------- | -------------
1 | Parent - 1 | NULL | parent-1
2 | Parent - 2 | NULL | parent-2
3 | Child-1- P - 1 | 1 | ch-1-p-1
4 | Child-1- P - 2 | 2 | ch-1-p-2
5 | sCh-1-Ch-1-P- 2 | 4 | sch-1-ch-1-p-2
To obtain children relationship I used the following method on the linkedin\\Category model.为了获得子关系,我在linkedin\\Category 模型上使用了以下方法。
public function children()
{
return $this->hasMany('linkedin\Category', 'cat_parent_id', 'id');
}
In my controller,在我的控制器中,
public function category(Category $category)
{
$categories = $category->first()->children;
return view('product.list', compact('categories'));
}
Here is my route这是我的路线
Route::get('/{category?}','ProductController@category');
I am able to fetch the first children using the following code.我可以使用以下代码获取第一个孩子。 It shows the following, when I visit the url, http://trump.localhost/parent-2
它显示以下内容,当我访问 url 时, http://trump.localhost/parent-2
Child-1- P - 2儿童 1- P - 2
However, it doesn't show anything when I visit http://trump.localhost/parent-2/ch-1-p-2但是,当我访问http://trump.localhost/parent-2/ch-1-p-2时它没有显示任何内容
It should show following, but I don't see it.它应该显示以下内容,但我没有看到。
sCh-1-Ch-1-P- 2 sCh-1-Ch-1-P-2
You have to adjust your route:您必须调整路线:
Route::get('{category1}/{category2?}/{category3?}/{category4?}',
'ProductController@category');
And your controller:还有你的控制器:
public function category(Category $category1, Category $category2 = null,
Category $category3 = null, Category $category4 = null) {
$category = collect(func_get_args())->filter()->last();
$categories = $category->children;
return view('product.list', compact('categories'));
}
in model在模型中
public function children()
{
return $this->hasMany('kblinked\Category', 'cat_parent_id');
}
in your controller send category id in argument then find that category;在您的控制器中,在参数中发送类别 ID,然后找到该类别;
public function category($category) // $category is id of category
{
$category = Category::findOrFail($category);
return view('product.list', compact('categories'));
}
in your view在你看来
@foreach($category->children as $child)
{{$child->name}}
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.