S
S
Sergey2016-12-08 18:47:21
MySQL
Sergey, 2016-12-08 18:47:21

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

2 answer(s)
L
LittleFatNinja, 2016-12-08
@LittleFatNinja

what is the problem?

S
Sergey, 2016-12-08
@badbizarre

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

Issues a request one to one as I need. But for some reason, if I do at the end of ->all() the result will be an array, and I need an object, tell me what to do?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question