原始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查询(派生的注释表)进行内部连接?
提前谢谢。如有任何答复,将不胜感激。
发布于 2016-02-11 09:18:55
join的别名是这样创建的:
$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']);https://stackoverflow.com/questions/35321309
复制相似问题