【问题标题】:Migration cakephp 2.x to 3.x grouped result from query将 cakephp 2.x 迁移到 3.x 分组查询结果
【发布时间】:2016-11-01 11:57:37
【问题描述】:

我用 cakephp2 编写了一段时间。我使用带有每年和每月计算值的表格。 例如

YEAR | MONTH | VALUENAME | VALUE 
2011 | 1     | value1    | 100
2011 | 2     | value1    | 120
2011 | 1     | value2    | 1234
2011 | 2     | value2    | 4342
etc.

现在我想获得每个“valuename”的年度总和值。 在 Cake2 中,我使用以下表达式来获得结果,其中我将年份作为数组键(这对我的观点很重要):

$yearvalues = $this->Aggregation->find('list', [
"fields" => ['Aggregation.value_name', 'Aggregation.sum_value', 'Aggregation.y'],
"group" => ['Aggregation.y', 'Aggregation.value_name']
]);

在我的“聚合”模型中,我得到以下信息:

public $virtualFields = array(
        'sum_value' => "sum(value)",
    );

结果如下:

Array
(
    [2011] => Array
        (
            [value1] => 1429.00
            [value2] => 1180.00
            [value3] => 0.00
            [value4] => 804.00
        )

    [2012] => Array
        (
            [value1] => 1878.00
            [value2] => 2793.00
            [value3] => 3900.00
            [value4] => 1606.00
        )
    ...
)

我现在如何在 Cake3 中获得相同的结果。我对如何以正确的方式处理查询对象有点困惑:-( 这就是我现在所做的:

$yearvalues->select(['Aggregation.value_name', 
'sum_value' => $yearvalues->func()->sum('Aggregation.value'), 'y'])
->group(['Aggregation.y', 'Aggregation.value_name']);

有人可以帮助我采取正确的方法吗?

谢谢 奥利弗

【问题讨论】:

    标签: cakephp formatting cakephp-3.0 query-builder


    【解决方案1】:

    您也可以在 CakePHP 3.x 中使用list finder,它支持类似的选项。

    $yearvalues
        ->find('list', [
            'keyField' => 'value_name',
            'valueField' => 'sum_value',
            'groupField' => 'y'
        ])
        ->select([
            'Aggregation.value_name', 
            'sum_value' => $yearvalues->func()->sum('Aggregation.value'),
            'Aggregation.y'
        ])
        ->group([
            'Aggregation.y',
            'Aggregation.value_name'
        ]);
    

    list finder 基本上只是添加了一个结果格式化程序,它将使用Collection::combine() 来格式化检索到的结果,这也是为什么你不使用字段选项的别名,在结果中只会有实体/数组带有属性/字段名称索引!

    另见

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 2018-02-02
      • 1970-01-01
      • 2023-03-29
      • 2016-04-04
      • 1970-01-01
      • 2020-11-24
      相关资源
      最近更新 更多