【发布时间】:2014-04-29 15:46:25
【问题描述】:
我需要从“orcamentos”表中获取“valor”字段的总和。 我正在使用它并且它正在工作,但我知道这不是正确的方法:
//function index() from OrcamentosController.php
$orcamentoSubprojetosTotal = $this->Orcamento->query(
"SELECT
SUM(Orcamento.valor) AS TotalOrcamentoSuprojetos
FROM
orcamentos AS Orcamento
WHERE
Orcamento.subprojeto_id IS NOT NULL;"
);
$this->set(compact('orcamentoSubprojetosTotal'));
我发现了这个问题cakephp sum() on single field(以及其他sum() function in cakephp query、using virtual fields to sum values in cakephp),但现在我将这一行添加到我的控制器中:
$this->Orcamento->virtualFields['total'] = 'SUM(Orcamento.valor)';
paginate() 停止工作并只显示一个条目,如下所示:
第 1 页,共 1 页,共显示 2 条记录中的 1 条记录,从记录 1 开始,到 2 结束
这是我的 index() 函数:
public function index($tipoOrcamento = null) {
$this->Orcamento->recursive = 0;
/*
$orcamentoSubprojetosTotal = $this->Orcamento->query(
"SELECT
SUM(Orcamento.valor) AS TotalOrcamentoSuprojetos
FROM
orcamentos AS Orcamento
WHERE
Orcamento.subprojeto_id IS NOT NULL;"
);
$this->set(compact('orcamentoSubprojetosTotal'));
*/
$this->set(compact('tipoOrcamento'));
if($tipoOrcamento == 'subtitulo'){
$this->set('orcamentos', $this->Paginator->paginate('Orcamento', array('Orcamento.subtitulo_id IS NOT NULL')));
}elseif($tipoOrcamento == 'subprojeto'){
$this->set('orcamentos', $this->Paginator->paginate('Orcamento', array('Orcamento.subprojeto_id IS NOT NULL')));
}else{
$this->set('orcamentos', $this->Paginator->paginate('Orcamento'));
}
}
我可以使用 query() 或者有人可以帮助我处理虚拟字段吗?
谢谢。
【问题讨论】:
-
其实我只需要一种访问总和的方法,我不需要虚拟字段。我用 cakePHP 做的方式好吗?
-
我的问题真的是执行 SUM 查询的正确方法是什么,很抱歉给您带来麻烦。