我正在開發(fā)一個(gè)Laravel with MySQL類似電子商務(wù)的網(wǎng)站,我需要按供應(yīng)商/商店顯示其類別下的所有產(chǎn)品。我嘗試了下面的代碼,但它重復(fù)了每個(gè)產(chǎn)品,如果產(chǎn)品屬于同一類別,則它不會(huì)分組在一個(gè)類別下。Controller:$products = Product::with('category')->where('store_id',$id)->get();View:@foreach($products as $product) {{ $product->category->name }} {{ $product->name }}@endforeachDatabase Structure:storeid | name---products - store_id is foreign key of store table and category_id is foreign key of categories tableid | store_id | category_id | name---categoriesid | name我期待的輸出:一類all products under this category第二類all products under this category
1 回答

哈士奇WWW
TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超6個(gè)贊
嘗試獲取類別并立即加載具有特定商店 ID 的產(chǎn)品
$categories = Category::with('products'=> function($query) use ($id) {
$query->where('store_id' , $id);
}])
->whereHas('products', function ($query) use ($id) {
$query->where('store_id' ,$id);
})
->get();
在視圖中首先循環(huán)您的類別,然后循環(huán)相關(guān)產(chǎn)品
@foreach($categories as $category)
{{ $category->name }}
@foreach($category->products as $product)
{{ $product->name }}
@endforeach
@endforeach
- 1 回答
- 0 關(guān)注
- 123 瀏覽
添加回答
舉報(bào)
0/150
提交
取消