How to specify the order of findAllByPk to match the id array order?




$id = array(20, 10, 15);

$models = Post::model()->findAllByPk($id);



The above code returns the records in ASC order by ID (i.e. 10, 15, 20). I want it to return the records in the order of the ids in the array (i.e. 20, 10, 15).

Without doing a foreach loop on the id array and performing a query on each id (to run 3 separate queries in this case) does anyone know of an easier way?

Have created this and it works well, but if anyone has a better solution, please let me know :)




$id = array(20, 10, 15);

$idCommaSeparated = implode(',',$id); 


$criteria = new CDbCriteria;

$criteria->order = "FIELD(id, $idCommaSeparated)";

$models = Post::model()->findAllByPk($id, $criteria);



Works perfect for me - fast and easy solution, thank you!. You solved my problem even before it have become the one ;)

Cheers,

B.