我正在开发一个Laravel with MySQL类似电子商务的网站,我需要按供应商/商店显示其类别下的所有产品。
我尝试了下面的代码,但它重复了每个产品,如果产品属于同一类别,则它不会分组在一个类别下。
Controller:
$products = Product::with('category')->where('store_id',$id)->get();
View:
@foreach($products as $product)
{{ $product->category->name }}
{{ $product->name }}
@endforeach
Database Structure:
store
id | name
---
products - store_id is foreign key of store table and category_id is foreign key of categories table
id | store_id | category_id | name
---
categories
id | name
我期待的输出:
一类
all products under this category
第二类
all products under this category
哈士奇WWW