我正在尝试通过 cakephp 使用 sum 函数执行查询,但没有返回预期的结果。
Controller 配置如下;
$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 语法中有错误;请检查与您的 MariaDB 服务器版本相对应的手册,了解要在附近使用的正确语法' 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
有人可以帮助我吗?
最佳答案
您可以尝试用 ->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)'
关于mysql - 用CakePHP中的SUM函数获取求咨询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39170176/