如何以cakephp-3方式重新编写查询?

时间:2016-02-10 16:57:29

标签: php sql cakephp cakephp-3.0

原始SQL查询:

SELECT Post.id, 
       Post.title, 
       Post.mark 
FROM   posts AS Post 
       INNER JOIN (SELECT post_id, 
                          Count(post_id) AS cnt 
                   FROM   comments 
                   WHERE  mark = 1 
                   GROUP  BY post_id) AS d 
               ON Post.id = d.post_id 
ORDER  BY d.cnt DESC 

我试图用cakephp-3方式编写这个原始的sql查询。

我用cakephp-3方式做了内部选择查询:

$comments = TableRegistry::get('Comments');
$query = $comments->find();
$query->select(['post_id','cnt'=>$query->func()->count('post_id')])
        ->where(['mark'=>1])
        ->group(['post_id']);

如何为此内部查询设置别名?那么,我怎么能用' Posts'或获得'帖子'的实例table如何使用内部sql查询(派生注释表)进行内连接?

提前致谢。任何答案都将受到高度赞赏。

1 个答案:

答案 0 :(得分:2)

连接的别名是这样的:

$query->innerJoin(['the_alias' => $subquery], $onConditions);

在你的情况下:

$comments = TableRegistry::get('Comments');
$subquery = $comments->find();
$subquery->select(['post_id' => 'post_id','cnt' => $query->func()->count('post_id')])
    ->where(['mark'=>1])
    ->group(['post_id']);

$postsTable->find()
    ->innerJoin(['d' => $subquery], ['Posts.id = d.post_id'])
    ->order(['d.cnt' => 'DESC']);