供应商/商店按类别对产品进行分组 - laravel

我正在开发一个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


心有法竹
浏览 59回答 1
1回答

哈士奇WWW

尝试获取类别并立即加载具有特定商店 ID 的产品$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();在视图中首先循环您的类别,然后循环相关产品@foreach($categories as $category)    {{ $category->name }}    @foreach($category->products as $product)        {{ $product->name }}    @endforeach@endforeach
打开App,查看更多内容
随时随地看视频慕课网APP