使用find()方法查询cakePHP

时间:2011-04-12 07:00:42

标签: php mysql sql find cakephp-1.2

如何将此查询转换为使用cakePHP的方法find()

查询:

SELECT Ch.id, COUNT( DU.d_id ) AS a, SUM(DU.d_id) AS b
FROM c AS Ch
LEFT JOIN du AS DU ON DU.c_id = Ch.id AND MONTH( DU.created ) = MONTH( NOW( ) )
LEFT JOIN d AS D ON DU.d_id = D.id
GROUP BY Ch.id

1 个答案:

答案 0 :(得分:1)

$Ch->find(
    'all',      
    'fields' => array(
               'Ch.id','COUNT( DU.d_id ) AS a', 'SUM(DU.d_id) AS b'),
    'joins'  => array(
                      array(
                            'table' => 'du',
                            'alias' => 'DU',
                            'type' => 'LEFT',
                            'conditions' => array('DU.c_id = Ch.id AND MONTH( DU.created ) = MONTH( NOW( )')),
                       array(
                            'table' => 'd',
                            'alias' => 'D',
                            'type' => 'LEFT',
                            'conditions' => array('DU.c_id = Ch.id AND MONTH( DU.created ) = MONTH( NOW( )')),
    'group' => 'Ch.id');          

我还没有测试过。关于Cake JOINs的更多信息:

http://book.cakephp.org/view/1018/find