doushan1157 2016-02-10 16:57
浏览 41
已采纳

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

Raw sql query:

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 

I'm trying to write this raw sql query in cakephp-3 way.

I have made the inner select query in cakephp-3 way:

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

How can i set alias for this inner query? Then, how can i do inner join with 'Posts' or getting the instance of 'Posts' table how can i do inner join with the inner sql query(the derived comments table)?

Thanks in advance. Any answer will be highly appreciated.

  • 写回答

1条回答 默认 最新

  • douqing5981 2016-02-11 09:18
    关注

    The alias for a join is made this way:

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

    In your case:

    $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']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口