Yii2.0数据库查询实例(三)
常用查询:
// WHERE admin_id >= 10 LIMIT 0,10 User::find()->select('*')->where(['>=', 'admin_id', 10])->offset(0)->limit(10)->all()
// SELECT `id`, (SELECT COUNT(*) FROM `user`) AS `count` FROM `post` $subQuery = (new Query())->select('COUNT(*)')->from('user'); $query = (new Query())->select(['id', 'count' => $subQuery])->from('post');
// SELECT DISTINCT `user_id` ... User::find()->select('user_id')->distinct();
更新:
//update(); //runValidation boolen 是否通过validate()校验字段 默认为true //attributeNames array 需要更新的字段 $model->update($runValidation , $attributeNames); //updateAll(); //update customer set status = 1 where status = 2 Customer::updateAll(['status' => 1], 'status = 2'); //update customer set status = 1 where status = 2 and uid = 1; Customer::updateAll(['status' => 1], ['status'=> '2','uid'=>'1']);
删除:
$model = Customer::findOne($id); $model->delete(); $model->deleteAll(['id'=>1]);
批量插入:
Yii::$app->db->createCommand()->batchInsert(UserModel::tableName(), ['user_id','username'], [ ['1','test1'], ['2','test2'], ['3','test3'], ])->execute();
查看执行sql
//UserModel $query = UserModel::find()->where(['status'=>1]); echo $query->createCommand()->getRawSql();