doutan1905 2016-07-27 11:35
浏览 39
已采纳

在Laravel中加载子类别时,查询结果加倍

I have strange problem and can't understand from where its came. On my page I have Top Level category. When I click on top level category is open page with all sub-categories which they have products.

The problem is that if I have 2 products in sub-category_1 I see two times sub-category_1 on the page.

This is the controller which I have

public function showSubCats($categoryId) {

$subcats = SubCategories::select('*', DB::raw('sub_category.sub_cat_id AS sub_cat_id'))
    ->leftJoin('products', function($join) {
             $join->on('products.sub_cat_id', '=', 'sub_category.sub_cat_id'); 
           })
        ->where('sub_category.category_id', '=', $categoryId)
        ->whereNotNull('products.sub_cat_id')
        ->get();

     return View::make('site.subcategory', [            
          'subcats' => $subcats             
     ]); 
}

Here is the view

 @foreach($subcats as $i => $subcategory)   

               // html
 @endforeach 

This is the result.. should be one sub-category with two products inside.. now I have two identical sub-cats.. same products, same id.. enter image description here

  • 写回答

1条回答 默认 最新

  • dounan9070 2016-07-27 11:42
    关注

    Change your query as

    $subcats = DB::table('sub_category as sc')
        ->leftJoin('products as p', 'p.sub_cat_id', '=', 'sc.sub_cat_id')//cross check this sc.sub_cat_id may be it si sc.id
        ->where('sc.category_id', '=', $categoryId)
        ->whereNotNull('p.sub_cat_id')
        ->select('*', DB::raw('sc.sub_cat_id AS sub_cat_id'))
        ->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失