yii2 查詢資料庫語法

流火行者發表於2015-12-14
 1         $query0 = ImGroupUser::find()->where(['gid'=>'56680dfc60b215d62104a4d8'])->select('user_client_id')->all();//AR
 2         $query1=ImGroupUser::findAll(['gid'=>'56680dfc60b215d62104a4d8']);//AR
 3         $query2=ImGroupUser::findBySql("select user_client_id from im_group_user where gid='56680dfc60b215d62104a4d8'")->all();//AR
 4         $query3=ImGroupUser::find()->where(['gid'=>'56680dfc60b215d62104a4d8'])->select('user_client_id')->asArray()->all();//Array
 5         $query = new yii\db\Query();
 6         $query4 = $query
 7             ->select(['user_client_id'])
 8             ->from(['im_group_user'])
 9             ->where(['gid'=>'56680dfc60b215d62104a4d8'])
10             ->all();//Array
11         $arr=[];
12         foreach($query4 as $key=>$value){
13 //            $arr[]=$value->user_client_id;
14             $arr[]=$value['user_client_id'];
15         }
16         var_dump($arr);

AR查詢結果預設為AR單條資料的物件,返回AR物件,用13行取物件結果集,返回Array物件用14行取結果集 注意query4查詢結果為陣列物件

1  $res = ImGroupUser::updateAll(['flag'=>0],['gid'=>$gid,'flag'=>1]);

更新資料庫欄位值。(將表中所有gid為$gid並且 flag=1的列的flag設為0)

有的時候查詢過程較為複雜,使用框架查詢效率低下,可以直接使用sql查詢:

1       $sql="select c_user.client_id,c_user.bapp_broker_id from c_user
2               where c_user.client_id!=''
3               and c_user.bapp_broker_id!='{$g32}'
4               and c_user.id in(select c_user_id from trade_fund_account where cust_id is not null and update_time between  date_sub(now(),interval 10 minute) and now() order by update_time desc)";
5         $res=Yii::$app->db->createCommand()->setSql($sql)->queryAll();

Yii查詢sql也可以這樣寫

 1 $res=Yii::$app->db->createCommand($sql)->queryAll(); 

相關文章