D
D
Dave2016-10-31 13:49:18
Yii
Dave, 2016-10-31 13:49:18

Bug in Yii2 - pagination doesn't work with orderBy()?

The documentation provides a very good example of how to work with pagination
. However, as soon as you set it, the calculation starts to fail. And it is buggy in this way - on some page it will display 15, on some 14. At the same time, the pageSize parameter is set to 15. But if you remove orderBy(), then everything works perfectly. It seems that I am not the first one who encountered this, but I could not find an adequate solution anywhere so far.orderBy('id DESC')

$query = Article::find()->where(['status' => 1])
                                   ->orderBy('id DESC');

Does anyone have a solution maybe?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Dave, 2016-10-31
@djay

The solution turned out to be quite trivial, you need to put groupBy() on the same column before orderBy().

$query->groupBy('items.id')
           ->orderBy('items.id DESC');

It is strange that the developers did not mention this in the documentation.

V
Vitaliy Orlov, 2016-10-31
@orlov0562

try adding orderBy after pagination, like this:

use yii\data\Pagination;

$query = Article::find()->where(['status' => 1]);
$count = $query->count();
$pagination = new Pagination(['totalCount' => $count]);

$articles = $query->orderBy('id DESC')->offset($pagination->offset)
    ->limit($pagination->limit)
    ->all();

A
Anton, 2016-10-31
@karminski

Try like this
orderBy(['id' => SORT_DESC]);

M
Maxim Timofeev, 2016-10-31
@webinar

If you use ActiveDataProvider, then sorting must be set in it, and not in query

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question