【问题标题】:How to can I multiple column same id group by ? - Laravel如何我可以通过多个列相同的 id 分组? - 拉拉维尔
【发布时间】:2018-07-06 14:27:55
【问题描述】:

我的数据库如下:

id |group_id |property_id |type     |
1  |   9     |     13     |property |
2  |   9     |     14     |property |
3  |   9     |     15     |property | 
4  |   9     |     14     |variant  |
5  |   8     |     14     |property |
6  |   8     |     15     |variant  |
7  |   8     |     13     |property |

我的代码如下:

 $stock_get_property = StockPropertyTemplate::groupBy('group_id')->selectRaw('count(type) as quantity , group_id')->where('type' , 'property')->get();
        $stock_get_variant = StockPropertyTemplate::groupBy('group_id')->selectRaw('count(type) as quantity , group_id')->where('type' , 'variant')->get();

我想要对它们进行总分组。 groupBy('group_id') 按 type="property" 和 "variant"。如何合并两个查询?

我要创建的数组输出如下;

id |group_id |count_property|count_variant|
1  |   9     |       3      |     1       |
2  |   8     |       2      |     1       |

我怎样才能用 Laravel 做到这一点?请帮帮我:(

【问题讨论】:

    标签: php arrays laravel laravel-5


    【解决方案1】:

    这个问题可以通过单个查询来解决:

    SELECT
        group_id,
        COUNT(NULLIF(type, 'variant')) as count_property,
        COUNT(NULLIF(type, 'property')) as count_variant
    FROM StockPropertyTemplate
    GROUP BY group_id;
    

    或者在 Laravel 风格中:

    $stock_get_property_and_variant = 
        StockPropertyTemplate::groupBy('group_id')
            ->selectRaw(
                "group_id,
                 COUNT(NULLIF(type, 'variant')) as count_property,
                 COUNT(NULLIF(type, 'property')) as count_variant"
            )
            ->orderBy('id', 'asc')
            ->get();
    

    SQL live code here

    【讨论】:

      【解决方案2】:

      我的解决方案如下;

          $stock_get_property = StockPropertyTemplate::groupBy('group_id')->selectRaw('count(type) as total_property , group_id ')->where('type' , 'property')->orderBy('id', 'asc')->get();
          $stock_get_variant = StockPropertyTemplate::groupBy('group_id')->selectRaw('count(type) as total_variant , group_id')->where('type' , 'variant')->orderBy('id', 'asc')->get();
      
         //assigning $variant array -> total_variant
         $variant = [];
         foreach ($stock_get_variant as  $row) {
             $variant[] = $row->total_variant;
         }
      
         //array push made
         $i = 0;
         $all_values = [];
         foreach ($stock_get_property as $row) {
             $all_values[] = array('group_id' => $row->group_id , 'total_property' => $row->total_property , 'total_variant' => $variant[$i]);
             $i++;
         }
      

      这段代码负责我的工作。

      【讨论】:

        猜你喜欢
        • 2020-06-05
        • 2016-07-28
        • 1970-01-01
        • 2020-09-02
        • 2019-04-21
        • 2020-03-03
        • 2017-08-22
        • 1970-01-01
        • 2016-02-06
        相关资源
        最近更新 更多