简体   繁体   中英

How can I convert this query in to CakePHP query?

How can I convert this query into a CakePHP query?

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

I have two controllers and two models, invoices and sales.

For aggregate functions like COUNT , you need to create virtual field.

$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

Use the following links as references:

Joining tables

Retrieving Your Data

Virtual fields

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM