dongquxiao8545 2016-01-18 12:23
浏览 12
已采纳

如何订购查询

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()
            ->select('*')
            ->from('form_fields')                                      
             ->where(array('not in', 'id', $sorted_array))
             ->andWhere('form_id=:form_id', array(':form_id'=>$form_id))
             ->queryAll();

$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?

  • 写回答

1条回答 默认 最新

  • douqilai4263 2016-01-18 13:35
    关注

    You can do using ->order() Add order( 'id' ) to your code this way:

     $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();
    

    otherwise if is not possibile build the query you need with query builder you can use

    Yii::app()->db->createCommand("select * from your_table")->queryAll();
    

    and for binding param

    Yii::app()->db->createCommand(
            'select * from your_table  where yuor_field =:your_param')->
          bindValue('your_param',$yuor_value)->queryAll();
    

    this returns all rows using a specified SQL statement

    $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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100