【发布时间】:2021-08-09 12:55:09
【问题描述】:
我有两个表:产品和类别。每个产品都有特定的类别。
products 表有 category_id。 类别表有 name 和 parent_id。
这是我的示例产品:iPhone 12。 在管理部分,我有 Apple 类别和 iPhone 子类别,然后我将产品 (iPhone 12) 放在 iPhone 子类别中。
在前端部分,我可以成功显示类别树无序列表,当我单击子类别 iPhone 时,产品 iPhone 12 显示正常,但当我单击类别 Apple 时,产品不显示。如何显示来自父类的数据,所以当我点击 Apple 类别或 iPhone 子类别以在两种情况下显示产品时?
这是我的代码:
型号类别
public function products()
{
return $this->hasMany('App\Models\Product');
}
public function children() {
return $this->hasMany('App\Models\Category', 'parent_id');
}
类别模型
public function products()
{
return $this->hasMany('App\Models\Product');
}
产品控制器
public function productCategory(Category $category) {
$categories = Category::with('children')->whereNull('parent_id')->where('status',1)->get();
$products = $category->products;
return view('products', compact('products', 'categories'));
}
路线
Route::get('/category/{category:slug}', 'App\Http\Controllers\ProductController@productCategory')->name('product.category');
产品视图:
<div class="content products">
<div class="container">
<div class="row">
<div class="col-md-3">
<div class="categories">
<ul>
@foreach($categories as $category)
<li>
<a href="{{ route('product.category', $category->slug) }}">{{ $category->name }}</a>
@if($category->children)
<ul>
@foreach($category->children as $child)
<li>
<a href="{{ route('product.category', $child->slug) }}">{{ $child->name }}</a>
</li>
@endforeach
</ul>
@endif
</li>
@endforeach
</ul>
</div>
</div>
<div class="col-md-9">
<div class="row">
@foreach($products as $product)
<div class="col-sm-4">
<div class="image">
<a href="{{ route('product', $product->slug) }}"><img class="img-fluid" src="{{ Storage::url($product->image) }}" /></a>
</div>
<div class="title">
<h3>{{ $product->title }}</h3>
</div>
</div>
@endforeach
</div>
</div>
</div>
</div>
</div>
【问题讨论】:
-
请显示您的类别型号。
-
你能在 productCategory 函数中获取 $slug 名称吗?
-
@Shahrukh 我更新了我的帖子。
-
@YasinPatel 是的,使用 dd($category);我正在获取包括蛞蝓在内的所有数据。
-
@user2519032,目前您正在获取所有产品吗? bcs 你没有在任何地方使用 $category
标签: laravel eloquent categories laravel-8 model-binding