Answer the question
In order to leave comments, you need to log in
How to make a nested query in yii2?
On Habré, I found such an example of how you can insert a subquery inside a query
$subQuery = (new Query)->select('COUNT(*)')->from('user');
$query = (new Query)->select(['id', 'count' => $subQuery])->from('post');
// $query represents the following SQL:
// SELECT `id`, (SELECT COUNT(*) FROM `user`) AS `count` FROM `post`
SELECT `id`, (SELECT COUNT(*) FROM `user` WHERE `user`.`id`=`post`.`autor_id`) AS `count` FROM `post`
Answer the question
In order to leave comments, you need to log in
Why do you need a nested query here?
Do a JOIN:
SELECT `post`.`id`, COUNT(`user`.`id`) AS `count`
FROM `post`
LEFT JOIN `user` ON `user`.`id` = `post`.`autor_id`
GROUP BY `post`.`id`
$query = (new Query)
->select(['post.id', 'count' => 'COUNT(user.id)'])
->from('post')
->leftJoin('user', 'user.id = post.autor_id');
->groupBy(['post.id']);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question