laravel 5.6: 假设每个产品有多个品牌,如何在table中显示每个产品和可用品牌

laravel 5.6: How to display each product and the available brand s in a table given that each product has multiple brands

我是 laravel 的新手,我正在尝试开发一个应用程序,其中有一个 table 部分列出了每种产品、可用品牌、可用数量,销售 prices.Each 产品有多个品牌

I have three tables involved:

1ST TABLE Items_master: this table stores the product names, buying and selling price

2ND TABLE Stock_quantities: this table stores the product quantities according to the shop by product_id and shop_id.

3RD TABLE item_brands: this table stores the brands of each product based on product_id and shop_id.

这是代码

获取产品名称、类别和项目数量的主查询

 $details=items_master::select('items_masters.id as 
   product_id','items_masters.name as item_name','items_masters.category','buying_price','selling_price','item_quantities.product_id','item_quantities.quantity','categories.id','categories.serial')       
 ->join('item_quantities','items_masters.id','=','item_quantities.item_id')
  ->join('categories','categories.id','=','items_masters.category')
   ->where([['item_quantities.shop_id', '=',$shop]] )
  ->groupBY('product_id')
   ->get();

获取产品 ID 的查询

    $product_ids = collect($details)->pluck('product_id');

查询产品品牌

   $brands = item_brands::whereIn('pid', $product_ids)
   ->where('shop_id', $shop)
   ->where('status', 0)
   ->get();

视图中的代码

   <div class="table-responsive">      
   <table class="table table-bordered table-striped" >
             <thead>
              <tr>
            
            <th>Item Name</th>
            <th>Item Brands</th>
           <th>Stock Qty</th>
           <th>Category</th>
            <th>Price</th>
            
            
              <th>Delete</th>
            </tr>
          </thead>
        <tbody>
          @foreach($details as $detail)
          <tr>
            <td>{{$detail->item_name}} </td>
            <td><div class="form-group">
          
                   
        @foreach($brands as $brand )

             <span>{{$brand->name}}</span>
         @endforeach

          
          </div>
         </td>
            <td>{{$detail->quantity.' '.$detail->units}} </td>
            <td >

            <td>{{$detail->category}} </td>
            <td >
            <b>Ksh. {{$detail->selling_price}}</b>
            
                          </td>
               </tr>
                       @endforeach
            </tbody>
          </table>

根据上面的代码,我得到了针对每个产品列出的 table 中所有产品的所有品牌。我需要每个产品只在其行上显示其品牌,例如

产品:平板电脑 |品牌:三星、苹果

产品:桌面 |品牌:惠普、联想

当前出现的是这个

产品:平板电脑 |品牌:三星、苹果、惠普、联想

产品:桌面 |品牌:三星、苹果、惠普、联想

你试过用集合的方式来限制foreach使用什么牌子吗?即:

@foreach($brands->where('pid', $detail->product_id) as $brand )
    <span>{{$brand->name}}</span>
@endforeach

由于您获得了每种产品的所有品牌,因此您只需选择当前 $detail 的品牌。

编辑:但老实说,我觉得所有 3 个查询都可以写入 1 个 eloquent 查询,但我必须看到所有 3 个具有关系的模型。