![](/img/trans.png)
[英]Laravel get all products from parent category and all it's sub-categories
[英]Display all products under sub-categories - Laravel 5.2
我需要顯示某個子類別下的所有產品。 我已經在主頁上設置了一個類別菜單,其中顯示了所有父類別及其子類別。 當我點擊子類別時,它會將我帶到子類別頁面,其 id 列在 URL 中。 我遇到的問題,是我不知道如何在該頁面上顯示該子類別下的所有產品嗎?
這是我顯示子類別頁面的路線:
Route::group(['middleware' => ['web']], function () {
Route::get('/category/{id}', [
'uses' => 'PagesController@categoryDisplay',
'as' => 'category.show'
]);
}
這是我的 ProductController.php,用於顯示子類別下的所有產品:
class PagesController extends Controller {
public function categoryDisplay($id) {
$products = Product::all();
//$cat_id = Product::where('cat_id', '=', 3);
return view('category.show', compact('products'));
}
}
這是我嘗試展示產品的頁面:
@extends('app')
@section('content')
<div class="container">
<h3 class="text-center">
Hi
@foreach($products as $product)
{{ $product->product_name }} <br>
@endforeach
</h3>
</div>
@endsection
我的類別模型:
class Category extends Model {
protected $table = 'categories';
protected $fillable = ['category'];
/**
* One sub category, belongs to a Main Category ( Or Parent Category ).
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function parent() {
return $this->belongsTo('App\Category', 'parent_id');
}
/**
* A Parent Category has many sub categories
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function children() {
return $this->hasMany('App\Category', 'parent_id');
}
/**
* One Category can have many Products.
*
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function product() {
return $this->hasMany('App\Product', 'id');
}
}
我的產品型號:
class Product extends Model {
protected $table = 'products';
protected $fillable = [
'product_name',
'price',
'cat_id'
];
/**
* One Product can have one Category.
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function category() {
return $this->hasOne('App\Category', 'id');
}
}
這就是我的產品表的樣子:
“cat_id”是產品子類別
正如您在我的控制器中看到的,如果我傳入一個實際數字,例如 3,它將顯示該 cat_id 下的所有產品,但顯然我需要它是動態的。
我明白了:我必須改變一些東西,比如我的路線:
Route::get('category/{id}','PagesController@displayProducts');
我的控制器:
class PagesController extends Controller {
public function displayProducts($id) {
$categories = Category::where('id', '=', $id)->get();
$products = Product::where('cat_id','=', $id)->get();
return view('category.show', compact('products', 'categories'));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.