如何将此查询转换为CakePHP查询?
SELECT COUNT(invoices.id) FROM invoices,sales
WHERE invoices.id=sales.invoice_id AND to_id='13' AND is_updated='0'
GROUP BY invoice_id
我有两个控制器和两个型号,发票和销售。
答案 0 :(得分:0)
尝试使用Cake的Cookbook解决方案:
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#prepared-statements
答案 1 :(得分:0)
对于像COUNT
这样的聚合函数,您需要创建虚拟字段。
$this->Invoice->virtualFields['total'] = 'COUNT(`Invoice`.`id`)';
$result = $this->Invoice->find('all', array(
'fields' => array('Invoice.total'),
'joins' => array(
array(
'table' => 'sales',
'alias' => 'Sale',
'type' => 'INNER',
'conditions' => array(
'Invoice.id = Sale.invoice_id',
)
)
),
'conditions' => array(
'to_id' => 13,
'is_updated' => 0
),
'group' => array('Sale.invoice_id')
));
pr($result); // Check your result
使用以下链接作为参考: