INNER JOIN与GROUP BY CakePHP方式

时间:2012-03-19 18:48:52

标签: php cakephp group-by inner-join

我正在为使用CakePHP 1.2的系统编写一个插件模块,我是该框架的新手。如何进行以下查询Cake方式?

SELECT a.id, a.name, COUNT(a.id) AS comments
FROM articles a LEFT JOIN comments c ON a.id = c.item_id
GROUP BY a.id
ORDER BY comments DESC;

我无法编辑文章或评论模型,但我在我的插件模型中尝试这个并且它没有给出相同的结果:

$this->loadModel('Article');
$options['fields'] = array('Article.id', 'Article.name', 
              'COUNT(Article.id) AS comments');
$options['joins'] = array(
    array('table' => 'comments',
          'alias' => 'c',
          'type' => 'INNER',
          'conditions' => array(
          'Article.id = c.item_id')
         ));
$options['group'] = array('Article.id');
$options['order'] = 'comments DESC';
$options['limit'] = 5;
$rows = $this->Article->find('all', $options);

另外,我不确定,但我认为Article类可能已经有了:

 public $actsAs = array('Containable');
 public $hasMany = array('Comment');

2 个答案:

答案 0 :(得分:3)

我认为您还需要在加入定义中添加foreignKey => FALSE

$options['joins'] = array(
    array('table' => 'comments',
          'alias' => 'c',
          'type' => 'INNER',
          'foreignKey' => FALSE,
          'conditions' => array('Article.id = c.item_id')
     )
);

此外,如果您自己强制加入,则应该通过传递recursive => FALSE作为选项或将unbindModel应用于每个关联模型来摆脱任何以前的Cake风格关联。

<强>更新

根据您在评论中所说的内容,我认为您需要:

$options['fields'] = array(
    'Article.id', 
    'Article.name', 
    'COUNT(DISTINCT c.id) AS comments'
);
$options['joins'] = array(
    array(
        'table' => 'comments',
        'alias' => 'c',
        'type' => 'LEFT OUTER',
        'foreignKey' => FALSE,
        'conditions' => array('Article.id = c.item_id')
    )
);
$options['group'] = array('Article.id');
$options['order'] = 'COUNT(DISTINCT c.id) DESC';
$rows = $this->Article->find('all', $options);

答案 1 :(得分:1)

非常意外的答案:

这个项目使用的CakePHP版本(我无能为力)是在2008-01-02发布的版本1.2.0.6311 beta,根据this article,Cake的模型查找方法中的功能组是仅在2008年5月添加