S
S
Sergey Beloventsev2016-08-08 10:52:28
Yii
Sergey Beloventsev, 2016-08-08 10:52:28

How to properly query an Active Record?

write a request

$years=Serial::find()->from(['new_table'=>Serial::find()->orderBy(['year'=>SORT_DESC])])->select('year')->groupBy('year')->orderBy(['year'=>SORT_DESC])->all();

get
SELECT `year`
 FROM (
SELECT * 
FROM `fl_serial` 
ORDER BY `year` DESC) `new_table` 
GROUP BY `year`

but I would like this
SELECT `year`
FROM (
SELECT *
FROM `fl_serial`
) `new_table`
GROUP BY `year`
ORDER BY `year` DESC

how to make it right

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2016-08-08
@qonand

Do you need to get a unique list of years? if so, then your initial query was not formed correctly, for these purposes you should not use grouping and a nested subquery, it is much easier to use DISTINCT, like this:
accordingly, the request for AR will be as follows

Serial::find()->select('year')->orderBy(['year'=>SORT_DESC])->distinct();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question