dougui1977 2017-10-03 07:34
浏览 924

如何在多个字段的laravel中进行分组

I am using laravel 5.4. Imagine I want to show some car advertising. I will get all car records from a table and load them into my page. Now I want to show multiple categories with counts in a sidebar (car types, car colors, car fuels) and I want to show the count for every category.

For example: we have 10 car ads, two of them are red, three are green and five of them are white. I want to have something like this in a sidebar:

red(2)
green(3)
white(5)

I did it with SQL groupBy:

        $colors = DB::table('advertisments')->select('color_name', DB::raw('count(color_name) as total_color'))->groupBy('color_name')->get();
        $gearboxes = DB::table('advertisments')->select('gearbox', DB::raw('count(gearbox) as total_gearbox'))->groupBy('gearbox')->get();
        $param = ['colors' => $colors,'gearboxes' => $gearboxes];
        return view('ads' , compact('ads','param'));

However, I have tens of categories and I can't do it with one groupBy so the number of queries is going to be too high. Is there a way to do it with a single query or with less queries?

  • 写回答

1条回答 默认 最新

  • douwen5951 2017-10-03 07:51
    关注

    You could use an array for make it easy to run through your different columns.

    $params = [];
    $columns = [
        'colors' => 'color_name',
        'gearboxes' => 'gearbox',
        // put your other columns in this array
    ];
    
    foreach($columns as $name => $column)
        $params[$name] = DB::table('advertisments')->select($column, DB::raw('count(' . $column . ') as total'))->groupBy($column)->get();
    
    return view('ads' , compact('ads','param'));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目