【问题标题】:How can i re-write the query in cakephp-3 way?如何以 cakephp-3 方式重新编写查询?
【发布时间】:2023-03-20 01:15:01
【问题描述】:

原始 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”进行内部连接或获取“Posts”表的实例,如何使用内部 sql 查询(派生的 cmets 表)进行内部连接?

提前致谢。任何答案将不胜感激。

【问题讨论】:

  • 我建议使用 Countercache 行为来跟踪评论计数查看更多 book.cakephp.org/3.0/en/orm/behaviors/counter-cache.html
  • 您可以像这样使用内部联接为子查询起别名 $this->Posts->find()->innerJoin(['d' => $query], $conditions);查看更多api.cakephp.org/3.2/…
  • 请格式化您的 sql,使其在发布问题时更具可读性。网上有大量免费的 sql 格式化程序。

标签: php sql cakephp cakephp-3.0


【解决方案1】:

连接的别名是这样生成的:

$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']);

【讨论】:

  • ['Posts.id = d.post_id'] 不起作用,我得到了 Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'd.post_id' in 'on clause' ['Posts.id = d.Comments__post_id'] 起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-03
  • 1970-01-01
  • 2013-07-13
  • 2019-12-14
  • 1970-01-01
相关资源
最近更新 更多