搜索
简帛阁>技术文章>Yii数据库操作

Yii数据库操作

参考:https://github.com/yii2-chinesization/yii2-zh-cn/blob/master/guide-zh-CN/db-dao.md


返回多行:

$command = $connection->createCommand('SELECT * FROM post');
$posts = $command->queryAll();
翻译单行:
$command = $connection->createCommand('SELECT * FROM post WHERE id=1');
$post = $command->queryOne();
查询多列:
$command = $connection->createCommand('SELECT title FROM post');
$titles = $command->queryColumn();
查询标量/计算值:
$command = $connection->createCommand('SELECT COUNT(*) FROM post');
$postCount = $command->queryScalar();
更新数据:
$command = $connection->createCommand('UPDATE post SET status=1 WHERE id=1');
$command->execute();
一次插入单行/多行:
// INSERT
	$connection->createCommand()->insert('user', [
	    'name' => 'Sam',
	    'age' => 30,
	])->execute();


// INSERT 一次插入多行
	$connection->createCommand()->batchInsert('user', ['name', 'age'], [
	    ['Tom', 30],
	    ['Jane', 20],
	    ['Linda', 25],
	])->execute();
更新:

$connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();

删除:

$connection->createCommand()->delete('user', 'status = 0')->execute();
预处理:
$command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
$command->bindValue(':id', $_GET['id']);
$post = $command->query();
一次预处理语句执行多次:

$command = $connection->createCommand('DELETE FROM post WHERE id=:id');
$command->bindParam(':id', $id);
	
$id = 1;
$command->execute();
	
$id = 2;
$command->execute();

建表:

$connection->createCommand()->createTable('post', [
	  'id' => 'pk',
	   'title' => 'string',
	   'text' => 'text',
]);


参考:query方式:https://githubcom/yii2chinesization/yii2zhcn/blob/master/guidezhCN/dbquerybuildermdActiv
参考:https://githubcom/yii2chinesization/yii2zhcn/blob/master/guidezhCN/dbdaomd返回多行:$command$connecti
一、执行原生太SQL的PDO方式。代码如下:$sql"";//原生态sql语句xx::model()>dbConnection>createCommand($sql)>execute
用:useyii\db\Query;$querynewQuery();查询:Query:$rows(new\yii\db\Query())>select(['code','name','pop
//1简单查询$adminAdmin::model()>findAll($condition,$params);$adminAdmin::model()>findAll(username:
本文介绍了Yii2——使用数据库操作汇总(增删查改、事务),具体如下:对象操作查询//1简单查询$adminAdmin::model()>findAll($condition,$params);
数据库访问(DAO)Yii包含了一个建立在PHPPDO之上的数据访问层(DAO)DAO为不同的数据库提供了一套统一的API其中ActiveRecord提供了数据库与模型(MVC中的M,Model)的
用:useyii\db\Query;$querynewQuery();查询:Query:$rows(new\yii\db\Query())>select(['code','name','pop
User::find()>all();此方法返回所有数据;User::findOne($id);此方法返回主键id1的一条数据(举个例子);User::find()>where(['nam
User::find()>all();此方法返回所有数据;User::findOne($id);此方法返回主键id1的一条数据(举个例子);User::find()>where(['nam