如何将此查询转换为CakePHP查询?

时间:2016-10-01 08:13:24

标签: php cakephp query-builder cakephp-2.6

如何将此查询转换为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

我有两个控制器和两个型号,发票和销售。

2 个答案:

答案 0 :(得分:0)

答案 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

使用以下链接作为参考:

Joining tables

Retrieving Your Data

Virtual fields