【问题标题】:Get the result of a consultation with the SUM function in CakePHP获取 CakePHP 中的 SUM 函数的咨询结果
【发布时间】:2016-08-26 15:51:08
【问题描述】:

我正在尝试通过 cakephp 使用 sum 函数执行查询,但没有返回预期结果。

控制器是这样配置的;

$PedItensOmitens = $PedItenstable->find('all', [
'fields' => array( 'item_prod, sum(item_qtd)as total'),
])->join(['b' =>[
'table' =>'om_itens',
'type' =>'INNER',
'conditions' => 'item_id = b.omi_item'
]
])->where(['b.omi_ordom ' => $ordemMontagem->om_id
])->Group(['item_prod '
]);

这个我返回消息“错误:SQLSTATE [42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;请检查手册 que Corresponds to your MariaDB server version 以了解在附近使用的正确语法' AS PedItens__sum ( item_qtd ) 完整的 FROM ped_itens PedItens INNER JOIN om_itens ' 在第 1 行"

用mysql在数据库中查询就是这样

select a.item_prod, sum(a.item_qtd)as total from ped_itens a inner join om_itens b on a.item_id = b.omi_item where b.omi_ordom = 1 group b a.item_prod

给我带来预期的结果

item_prod - 总计

7 - 2400.00

9 - 5292.00

10 - 6492.00

有人可以帮我吗?

【问题讨论】:

    标签: mysql cakephp cakephp-3.x


    【解决方案1】:

    您可以尝试用->select 替换fields 数组。比如:

    $PedItensOmitens = $PedItenstable->find()
        ->select([
            'item_prod' => 'item_prod',
            'total' => 'sum(item_qtd)'
        ])
        ->join([
            'b' =>[
                'table' =>'om_itens',
                'type' =>'INNER',
                'conditions' => 'item_id = b.omi_item'
            ]
        ])
        ->where(['b.omi_ordom ' => $ordemMontagem->om_id])
        ->Group(['item_prod'
    ]);
    

    在 Cake 查询中指定您从哪些表中选择可能也是一个好主意,类似于您在原始 SQL 中的表。所以在选择中:

    'item_prod' => 'a.item_prod', // where a is your model alias
    'total' => 'sum(a.item_qtd)'
    

    【讨论】:

    猜你喜欢
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    相关资源
    最近更新 更多