我有一个数组$sorted_array
它的值是
Array ( [0] => 3 [1] => 1 [2] => 6 )
现在基于 $sorted_array 我创建了一个数组
$first_array = Yii::app()->db->createCommand()
->select('*')
->from('form_fields')
->where(array('not in', 'id', $sorted_array))
->andWhere('form_id=:form_id', array(':form_id'=>$form_id))
->queryAll();
$sorted_array
值是表 form_fields
的 id(主键)。
当我运行此查询时,我得到数组 $first_array
但不是按照我想要的顺序。即,我将按顺序获得一个数组 $id=1,3,6。
现在我想要的顺序是 3,1,6(与 $sorted_array
完全相同)。我怎样才能按这个顺序获得$first_array
?
最佳答案
您可以使用 ->order() 将 order( 'id' ) 添加到您的代码中:
$first_array = Yii::app()->db->createCommand()
->select('*')
->from('form_fields')
->where(array('not in', 'id', $sorted_array))
->andWhere('form_id=:form_id', array(':form_id'=>$form_id))
->order('id')
->queryAll();
否则,如果无法使用查询构建器构建所需的查询,则可以使用
Yii::app()->db->createCommand("select * from your_table")->queryAll();
以及绑定(bind)参数
Yii::app()->db->createCommand(
'select * from your_table where yuor_field =:your_param')->
bindValue('your_param',$yuor_value)->queryAll();
这将使用指定的 SQL 语句返回所有行
$sql = "select * from form_fields
where id not in (3,1,6)
and form_id = " . $form_id .
"order by field(id, 3,6,1);";
$first_array = Yii::app()->db->createCommand($sql)->queryAll();
关于php - 如何订购查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34854708/