YII DB ORM原生入门查询总结

YII DB 原生语句,通用操作的入门总结

原生语句

调用yii\db\Command执行纯sql语句

查询

queryXXX:结果查询;

常用的:queryAll=>所有结果集    
queryOne=>返回一行(第一行),
queryColumn=>返回一列(第一列)
//匹配所有 返回[[列=>值]]的数组
 $result = Yii::$app->db
 			->createCommand('SELECT * FROM country WHERE code=\'CN\'')
 			->queryAll();

绑定参数

使用带参数的SQL语句,可防止SQL注入攻击,其采用预处理语句实现。
参数占位符:以冒号开头的字符串 如:id

绑定形式:
bindValue():单个参数值  如 bindValue(':id', $_GET['id])
bindValues():多个参数值 数组 如 bindValues([':id'=>$_GET['id, ':status'=>1])
bindParam():绑定单个参数 单支持参数引用
$result = Yii::$app->db->createCommand('SELECT * FROM country WHERE code=:code')
                ->bindValues(['code'=>'CN'])
                ->queryOne();
$code = '';
$query = Yii::$app->db->createCommand('SELECT * FROM country WHERE code=:code')
                ->bindParam(':code', $code);
$code = 'CN';
$result = $query->queryOne();

$code = 'US';
$result = $query->queryOne();

非查询语句

非查询用yii\db\Command::execute() 且 返回影响到的行数

$query = Yii::$app->db
->createCommand('UPDATE country SET population=19886000 WHERE code=\'AU\'')
->execute();

可以使用insert(), update(), delete构建SQL,
批量插入batchInsert(table name, column names, column values)
例如:

//insert (table name, column values)
$query = Yii::$app->db->createCommand()->insert(
        'country',
        ['code'=>'AF', 'name'=>'Afghanistan', 'population'=>18886000])
        ->execute();

//update (table name, column values, condition)
$query = Yii::$app->db->createCommand()->update('country',['population'=>20086000],'code=\'AF\'')
        ->execute();

//delete (table name, condition)
$query = Yii::$app->db->createCommand()->delete('country','code=\'AF\'')
        ->execute();
        

db事务

 $db = Yii::$app->db;
 $transaction = $db->beginTransaction();

 try {
     //TODO:executing SQL statements ...
     $db->createCommand("update city set status=1 WHERE city_id=1")->execute();
     $transaction->commit();
 } catch (\Throwable $e) {
     $transaction->rollBack();
     echo $e->getMessage();
 }

你可能感兴趣的:(YII)