为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
心有法竹 2023-11-03 16:01:08
我正在开发一个Laravel with MySQL类似电子商务的网站,我需要按供应商/商店显示其类别下的所有产品。我尝试了下面的代码,但它重复了每个产品,如果产品属于同一类别,则它不会分组在一个类别下。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贡献1799条经验 获得超6个赞

尝试获取类别并立即加载具有特定商店 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


查看完整回答
反对 回复 2023-11-03
  • 1 回答
  • 0 关注
  • 58 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信