laravel 5.6:鉴于每种产品都有多个品牌,如何在表格中显示每种产品和可用品牌

时间:2019-02-08 17:21:08

标签: laravel laravel-5.6

我是laravel的新手,我正在尝试开发一个应用程序,该应用程序的一部分带有表格,该表格列出了每种产品,可用的品牌,可用的数量,售价。每种产品都有多个品牌< / p>

  

我涉及三个表:

     

1ST表Items_master:此表存储产品名称,买卖价格

     

第二张表库存数量:此表根据商店按照product_id和shop_id存储产品数量。

     

3RD表item_brands:此表根据product_id和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>

鉴于上面的代码,我在针对每种产品列出的表格中获得了所有产品的所有品牌。我需要每个产品仅在其行上展示其品牌,例如

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

产品:台式机|品牌:HP,联想

目前这是什么

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

产品:台式机|品牌:三星,苹果,惠普,联想

1 个答案:

答案 0 :(得分:1)

您是否尝试过使用收集方法来约束foreach中使用了哪些品牌? IE:

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

由于每种产品都有所有品牌,因此您只需选择当前$detail的品牌即可。

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