Answer the question
In order to leave comments, you need to log in
How to translate mysql query to Active Record Yii2?
There is a query that worked fine for a long time on my handwritten site until the time when I wanted to cut all my sites under Yii2 at the same time and deal with this basis.
SELECT i.id, i.src_small as src FROM ideas i JOIN ideas_filters f USING (id) WHERE f.filter IN ($array) GROUP BY i.id HAVING COUNT(DISTINCT f.filter) = '.count($array),' ORDER BY i.id DESC
$query = Ideas::find()->select('id, src_small')->where(['theme' => $theme->id])->orderBy('id DESC');
Answer the question
In order to leave comments, you need to log in
Ideas::find()
->select(['i.id', 'i.src_small as src']) // Возможно просто одной сторокой select('i.id, i.src_small as src'). Проверить под рукой правильность нет.
->from(['i' => Ideas::tableName()])
->join('JOIN', ['f' => IdeasFilters::tableName()], 'f.id=i.id') // USING в yii2 нету поэтому так
->where(['f.filter' => $array]) // $array чистый массив в 1 колонку с числовыми индексами 0,1,2 etc. В общем обычный массив вида [23,43,52]
->groupBy('i.id')
->having(['COUNT(DISTINCT f.filter)' => count($array)])
->orderBy(['i.id' => SORT_DESC])
->all(); // или one() смотря что нужно.
i.src_small as src
). However, Yii will not allow you to create this property "on the fly", and therefore you need to register it.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question