How to Order a query

I have an array $sorted_array its value is

Array ( [0] => 3 [1] => 1 [2] => 6 )

Now based on the $sorted_array i created an array

$first_array = Yii::app()->db->createCommand()



    	         ->where(array('not in', 'id', $sorted_array))

    	         ->andWhere('form_id=:form_id', array(':form_id'=>$form_id))


$sorted_array value is the id (Primary key) of table form_fields.

When i run this query i get the array $first_array but not in the order in which i want it. ie, I will get an array in order $id=1,3,6.

Now my wanted order is 3,1,6 (exactly as $sorted_array). How can i get $first_array in that order?

You can Try making a temporary table with, values as in $sorted_array, then apply sort on this table, joining with original one.


i tried something like this

$SQL="SELECT * FROM form_fields WHERE id NOT IN {$sorted_array}  ORDER BY FIELD (id, {$sorted_array})";





but it gave me an error [font=Verdana][size=4]Array to string conversion[/size][/font]

Hi, Firstly you require Order 3-1-6 Right ??.. And you are rejecting same in condition { NOT IN ($sorted_array) }. This way you are not going right. And order applies on a column, for this here i have a idea,…

    $sorted_array=Array (3,1,6);







	    foreach($sorted_array as $key=>$value){




			throw new CDbException("Temp Table Insertion Fail");



	    $first_array = $connection->createCommand()


							    ->from('form_fields as b')

							    ->leftJoin("temp as t","")

							    ->where(array('in', '', $sorted_array))










    catch(Exception $e){


	    echo $e->getMessage();