【问题标题】:laravel 5.6: How to display each product and the available brand s in a table given that each product has multiple brandslaravel 5.6:鉴于每个产品都有多个品牌,如何在表格中显示每个产品和可用品牌
【发布时间】:2019-02-08 17:21:08
【问题描述】:

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

我涉及三个表:

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

2ND TABLE Stock_quantities:该表按product_id和shop_id按店铺存储产品数量。

3RD TABLE 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>

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

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

产品:台式机 |品牌:惠普、联想

目前是这样的

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

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

【问题讨论】:

    标签: laravel laravel-5.6


    【解决方案1】:

    您是否尝试过使用集合方法来限制 foreach 中使用哪些品牌?即:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      • 2018-08-26
      • 1970-01-01
      • 2015-09-23
      • 2012-08-11
      • 2011-12-17
      • 2010-10-16
      相关资源
      最近更新 更多