[英]How can i re-write the query in cakephp-3 way?
原始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']);
如何为内部查询设置别名? 然后,如何使用“帖子”进行内部联接或获取“帖子”表的实例,如何使用内部sql查询(派生的注释表)进行内部联接?
提前致谢。 任何答案将不胜感激。
联接的别名是这样创建的:
$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']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.