我需要从“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'));
}
}
我可以使用查询()或有人可以帮我处理虚拟字段吗?
谢谢。
答案 0 :(得分:1)
当然,当您使用SUM时,您将获得单个记录
你可以做两件事:
virtualField
调用之前创建find()
,并在查询之后取消设置。'fields' => arra(...)
并列出您需要检索的字段,而不是当您不想SUM时列出虚拟字段答案 1 :(得分:1)
virtual field适用于以下内容:
public $virtualFields = array(
'name' => 'CONCAT(User.first_name, " ", User.last_name)'
);
如果虚拟字段来自不属于/单行的内容 - 它将不会执行您期望的内容,这可以通过查找调用paginate
生成的次要效果来证明。
相反,使用field方法并传入表达式:
$integer = $Model->field(
'SUM(valor)',
array('NOT' => array('subprojeto_id' => null))
);
将执行:
SELECT SUM(valor) from x where NOT (subprojecto_id IS NULL);
这也将返回一个标量值,而问题中显示的调用查询将返回一个嵌套数组。