I am trying to get all model item using CActiveDataProvider in Yii. These items are sorted by rand() and a pagination of 20 is applied. Here's my code:

    $i = new CActiveDataProvider('Item', 
        array(  
            'criteria' => array(
                'order'=>'RAND()',
            ),
            'pagination' => array( 
                'pageSize' => 20 ,
            ),
        )
    );

My problem is that the items are reordered whenever I change pages via pagination link. Is there any way around this?

Thank you.

有帮助吗?

解决方案

That is not a Yii problem, it is a PHP MySQL Logic problem.

First of all, I would suggest for performance improvement to use SELECT RAND() FROM Table, instead of ORDER BY RAND().

That will be a major improvement.

Secondly, MYSQL RAND is something not really worth it as most users don't come back repeatedly to the same pages expecting different results from the same result set. And it is just not possible unless*..

Before moving into the unless, the preferred way to do this would be to simulate it by perhaps using one of your pre-defined keys, and randomly selecting one and order it randomly as well by ASC\DESC.

Say you have a 'date' and a 'order' field. Pick one of the two randomly, and ASC\DESC randmoly.

*unless you save the entire result set in a SESSION, or you control your pagination via ajax, and don't use the Yii integrated one.

Since you are using Yii, I would suggest my FAKE RANDOM Option.

:)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top