Answer the question
In order to leave comments, you need to log in
YII2 how to query Active Record?
I don’t understand how to make such a query in YII2
SELECT
`np_recepty`.*,
(SELECT count(*)
FROM `np_recepty_ingredients` s1
WHERE s1.recept_id = s.recept_id and `ingredient_id` IN (144,274,322)) as `cnt`
FROM `np_recepty_ingredients` s
LEFT JOIN `np_recepty` ON `np_recepty`.`id` = s.`recept_id`
GROUP BY `np_recepty`.`id`
HAVING `cnt` > 0
ORDER BY `cnt` DESC
Answer the question
In order to leave comments, you need to log in
$subQuery = (new \yii\db\Query())
->select('COUNT(*)')
->where('s1.`recept_id` = `np_recepty_ingredients`.`recept_id`')
->from('np_recepty_ingredients s1');
$query = (new \yii\db\Query())
->select(['np_recepty.*', 'cnt' => $subQuery])
->from('np_recepty_ingredients')
->join('LEFT JOIN','`np_recepty` ON `np_recepty`.`id` = `np_recepty_ingredients`.`recept_id`')
->groupBy('`np_recepty`.`id`')
->having('cnt > 0')
->orderBy('cnt DESC');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question