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 删除 $model = User::find($id); $model->delete(); 带有条件的删除 $connection ->createCommand() ->delete('tbl_user', 'status = 0') ->execute(); 使用 Query 查询删除 $connection ->createCommand('DELETE FROM tbl_user WHERE userid=:userid') ->execute(); 使用预处理语句删除 方法一 $model = $connection->createCommand('DELETE FROM tbl_user WHERE userid=:userid'); $model->bindParam(':userid', $userid); $userid = 5; $model->execute(); 方法二 在 Yii2 使用预处理语句删除多个用户。 $model = $connection->createCommand('DELETE FROM tbl_user WHERE userid=:userid'); $model->bindParam(':userid', $userid); // delete user 1 $userid = 1; $model->execute(); // delete user 2 $userid = 2; $model->execute(); 查找并且删除 $user = User::findOne(2); $user->delete(); // 输出语句 // DELETE FROM `tbl_user` WHERE `id`='2' deleteAll() 删除多个 如果你不指定任何条件下,该方法将删除表中的所有行。例如删除用户表中状态条件是 active 和年龄大于20的用户。 方法一 User::deleteAll('status = :status AND age > :age', [':age' => 20, ':status' => 'active']); //Output Query //DELETE FROM `tbl_user` WHERE status = 'active' AND age > 20 方法二 User::deleteAll([ 'and', 'type = :type_id', ['not in', 'usercategoryid', $categoriesList] ], [ ':type_id' => 2 ]); //Output Query //DELETE FROM `tbl_user` WHERE (type = 2) AND (`usercategoryid` NOT IN (1, 2, 3))
批量插入:
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();