Database access (DAO)
Yii includes a data access layer (DAO) built on PHP PDO. DAO provides a unified API for different databases. ActiveRecord provides database and model (M, Model in MVC) Interaction, QueryBuilder is used to create dynamic query statements. DAO provides simple and efficient SQL queries, which can be used in various places to interact with the database.
Yii supports the following databases (DBMS) by default:
Configuration
To start using the database, you first need to configure the database connection component. This is achieved by adding the db component to the application configuration (the "basic" Web application is config/web.php). DSN (Data Source Name) is the data source name, used to specify Database information. As shown below:
return [ // ... 'components' => [ // ... 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=mydatabase', // MySQL, MariaDB //'dsn' => 'sqlite:/path/to/database/file', // SQLite //'dsn' => 'pgsql:host=localhost;port=5432;dbname=mydatabase', // PostgreSQL //'dsn' => 'cubrid:dbname=demodb;host=localhost;port=33000', // CUBRID //'dsn' => 'sqlsrv:Server=localhost;Database=mydatabase', // MS SQL Server, sqlsrv driver //'dsn' => 'dblib:host=localhost;dbname=mydatabase', // MS SQL Server, dblib driver //'dsn' => 'mssql:host=localhost;dbname=mydatabase', // MS SQL Server, mssql driver //'dsn' => 'oci:dbname=//localhost:1521/mydatabase', // Oracle 'username' => 'root', //数据库用户名 'password' => '', //数据库密码 'charset' => 'utf8', ], ], // ... ];
Please refer to the PHP manual for more information about the DSN format. After configuring the connection component, it can be accessed using the following syntax:
$connection = \Yii::$app->db;
Please refer to yiidbConnection for a list of configurable properties. If you want to connect to the database through ODBC, you need to configure the yiidbConnection::driverName attribute, for example:
'db' => [ 'class' => 'yii\db\Connection', 'driverName' => 'mysql', 'dsn' => 'odbc:Driver={MySQL};Server=localhost;Database=test', 'username' => 'root', 'password' => '', ],
Note: If you need to use multiple databases at the same time, you can define multiple connection components:
return [ // ... 'components' => [ // ... 'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=mydatabase', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ], 'secondDb' => [ 'class' => 'yii\db\Connection', 'dsn' => 'sqlite:/path/to/database/file', ], ], // ... ];
is used in code via:
$primaryConnection = \Yii::$app->db; $secondaryConnection = \Yii::$app->secondDb;
If you don’t want to define the database connection as a global application component, you can initialize it directly in the code:
$connection = new \yii\db\Connection([ 'dsn' => $dsn, 'username' => $username, 'password' => $password, ]); $connection->open();
Tip: If you need to perform additional SQL queries after creating the connection, you can add the following code to the application configuration file:
return [ // ... 'components' => [ // ... 'db' => [ 'class' => 'yii\db\Connection', // ... 'on afterOpen' => function($event) { $event->sender->createCommand("SET time_zone = 'UTC'")->execute(); } ], ], // ... ];
If executing SQL does not return any data, you can use the execute method in the command:
$command = $connection->createCommand('UPDATE post SET status=1 WHERE id=1'); $command->execute();
You can use the insert, update, and delete methods, which will generate appropriate SQL based on the parameters and execute them.
// INSERT $connection->createCommand()->insert('user', [ 'name' => 'Sam', 'age' => 30, ])->execute(); // INSERT 一次插入多行 $connection->createCommand()->batchInsert('user', ['name', 'age'], [ ['Tom', 30], ['Jane', 20], ['Linda', 25], ])->execute(); // UPDATE $connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute(); // DELETE $connection->createCommand()->delete('user', 'status = 0')->execute();
Referenced table name and column name
Most of the time use the following syntax to safely reference table and column names:
$sql = "SELECT COUNT($column) FROM {{table}}"; $rowCount = $connection->createCommand($sql)->queryScalar();
The above code $column will be converted to reference the appropriate column name, and {{table}} will be converted to reference the appropriate table name. The table name has a special variable {{%Y}}. If a table prefix is set, use this variant to automatically add a prefix before the table name:
$sql = "SELECT COUNT($column) FROM {{%$table}}"; $rowCount = $connection->createCommand($sql)->queryScalar();
If the table prefix is set as follows in the configuration file, the above code will query the results in the tbl_table table:
return [ // ... 'components' => [ // ... 'db' => [ // ... 'tablePrefix' => 'tbl_', ], ], ];
Another option for manually quoting table and column names is to use yiidbConnection::quoteTableName() and yiidbConnection::quoteColumnName():
$column = $connection->quoteColumnName($column); $table = $connection->quoteTableName($table); $sql = "SELECT COUNT($column) FROM $table"; $rowCount = $connection->createCommand($sql)->queryScalar();
Prepared statements
To safely pass query parameters, you can use preprocessing statements. First, you should use: placeholder, and then bind the variable to the corresponding placeholder:
$command = $connection->createCommand('SELECT * FROM post WHERE id=:id'); $command->bindValue(':id', $_GET['id']); $post = $command->query();
Another usage is to prepare a prepared statement once and execute multiple queries:
$command = $connection->createCommand('DELETE FROM post WHERE id=:id'); $command->bindParam(':id', $id); $id = 1; $command->execute(); $id = 2; $command->execute();
Tip, it is more efficient to bind variables before execution and then change the value of the variable in each execution (generally used in loops).
Transactions
When you need to execute multiple related queries sequentially, you can encapsulate them into a transaction to protect data consistency. Yii provides a simple interface to implement transaction operations. Execute the SQL transaction query statement as follows:
$transaction = $connection->beginTransaction(); try { $connection->createCommand($sql1)->execute(); $connection->createCommand($sql2)->execute(); // ... 执行其他 SQL 语句 ... $transaction->commit(); } catch(Exception $e) { $transaction->rollBack(); }
We start a transaction through yiidbConnection::beginTransaction() and catch the exception through try catch. When the execution is successful, the transaction is submitted and ended through yiidbTransaction::commit(). When an exception occurs and the transaction fails, the transaction is performed through yiidbTransaction::rollBack(). Rollback.
You can also nest multiple transactions if necessary:
// 外部事务 $transaction1 = $connection->beginTransaction(); try { $connection->createCommand($sql1)->execute(); // 内部事务 $transaction2 = $connection->beginTransaction(); try { $connection->createCommand($sql2)->execute(); $transaction2->commit(); } catch (Exception $e) { $transaction2->rollBack(); } $transaction1->commit(); } catch (Exception $e) { $transaction1->rollBack(); }
Note that the database you use must support Savepoints to execute correctly. The above code can be executed in all relational data, but security can only be guaranteed by supporting Savepoints.
Yii also supports setting isolation levels for transactions. When executing a transaction, the default isolation level of the database will be used. You can also specify the isolation level for things. Yii provides the following constants as commonly used isolation levels
You can use the above constants or use a string command and execute the command in the corresponding database to set the isolation level. For example, the effective command for postgres is SERIALIZABLE READ ONLY DEFERRABLE.
注意:某些数据库只能针对连接来设置事务隔离级别,所以你必须要为连接明确制定隔离级别.目前受影响的数据库:MSSQL SQLite
注意:SQLite 只支持两种事务隔离级别,所以你只能设置READ UNCOMMITTED 和 SERIALIZABLE.使用其他隔离级别会抛出异常.
注意:PostgreSQL 不允许在事务开始前设置隔离级别,所以你不能在事务开始时指定隔离级别.你可以在事务开始之后调用yii\db\Transaction::setIsolationLevel() 来设置.
关于隔离级别[isolation levels]: http://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels
数据库复制和读写分离
很多数据库支持数据库复制 http://en.wikipedia.org/wiki/Replication_(computing)#Database_replication">database replication来提高可用性和响应速度. 在数据库复制中,数据总是从主服务器 到 从服务器. 所有的插入和更新等写操作在主服务器执行,而读操作在从服务器执行.
通过配置yii\db\Connection可以实现数据库复制和读写分离.
[ 'class' => 'yii\db\Connection', // 配置主服务器 'dsn' => 'dsn for master server', 'username' => 'master', 'password' => '', // 配置从服务器 'slaveConfig' => [ 'username' => 'slave', 'password' => '', 'attributes' => [ // use a smaller connection timeout PDO::ATTR_TIMEOUT => 10, ], ], // 配置从服务器组 'slaves' => [ ['dsn' => 'dsn for slave server 1'], ['dsn' => 'dsn for slave server 2'], ['dsn' => 'dsn for slave server 3'], ['dsn' => 'dsn for slave server 4'], ], ]
以上的配置实现了一主多从的结构,从服务器用以执行读查询,主服务器执行写入查询,读写分离的功能由后台代码自动完成.调用者无须关心.例如:
// 使用以上配置创建数据库连接对象 $db = Yii::createObject($config); // 通过从服务器执行查询操作 $rows = $db->createCommand('SELECT * FROM user LIMIT 10')->queryAll(); // 通过主服务器执行更新操作 $db->createCommand("UPDATE user SET username='demo' WHERE id=1")->execute();
注意:通过yii\db\Command::execute() 执行的查询被认为是写操作,所有使用yii\db\Command来执行的其他查询方法被认为是读操作.你可以通过$db->slave得到当前正在使用能够的从服务器.
Connection组件支持从服务器的负载均衡和故障转移,当第一次执行读查询时,会随即选择一个从服务器进行连接,如果连接失败则又选择另一个,如果所有从服务器都不可用,则会连接主服务器。你可以配置yii\db\Connection::serverStatusCache来记住那些不能连接的从服务器,使Yii 在一段时间[[yii\db\Connection::serverRetryInterval].内不会重复尝试连接那些根本不可用的从服务器.
注意:在上述配置中,每个从服务器连接超时时间被指定为10s. 如果在10s内不能连接,则被认为该服务器已经挂掉.你也可以自定义超时参数.
你也可以配置多主多从的结构,例如:
[ 'class' => 'yii\db\Connection', // 配置主服务器 'masterConfig' => [ 'username' => 'master', 'password' => '', 'attributes' => [ // use a smaller connection timeout PDO::ATTR_TIMEOUT => 10, ], ], // 配置主服务器组 'masters' => [ ['dsn' => 'dsn for master server 1'], ['dsn' => 'dsn for master server 2'], ], // 配置从服务器 'slaveConfig' => [ 'username' => 'slave', 'password' => '', 'attributes' => [ // use a smaller connection timeout PDO::ATTR_TIMEOUT => 10, ], ], // 配置从服务器组 'slaves' => [ ['dsn' => 'dsn for slave server 1'], ['dsn' => 'dsn for slave server 2'], ['dsn' => 'dsn for slave server 3'], ['dsn' => 'dsn for slave server 4'], ], ]
上述配置制定了2个主服务器和4个从服务器.Connection组件也支持主服务器的负载均衡和故障转移,与从服务器不同的是,如果所有主服务器都不可用,则会抛出异常.
注意:当你使用yii\db\Connection::masters来配置一个或多个主服务器时,Connection中关于数据库连接的其他属性(例如:dsn,username, password)都会被忽略.
事务默认使用主服务器的连接,并且在事务执行中的所有操作都会使用主服务器的连接,例如:
// 在主服务器连接上开始事务 $transaction = $db->beginTransaction(); try { // 所有的查询都在主服务器上执行 $rows = $db->createCommand('SELECT * FROM user LIMIT 10')->queryAll(); $db->createCommand("UPDATE user SET username='demo' WHERE id=1")->execute(); $transaction->commit(); } catch(\Exception $e) { $transaction->rollBack(); throw $e; }
如果你想在从服务器上执行事务操作则必须要明确地指定,比如:
$transaction = $db->slave->beginTransaction();
有时你想强制使用主服务器来执行读查询,你可以调用seMaster()方法.
$rows = $db->useMaster(function ($db) { return $db->createCommand('SELECT * FROM user LIMIT 10')->queryAll(); });
你也可以设置$db->enableSlaves 为false来使所有查询都在主服务器上执行.
你可以通过 yii\db\Schema实例来获取Schema信息:
$schema = $connection->getSchema();
该实例包括一系列方法来检索数据库多方面的信息:
$tables = $schema->getTableNames();
更多信息请参考yii\db\Schema
修改模式
除了基础的 SQL 查询,yii\db\Command还包括一系列方法来修改数据库模式:
使用示例:
// 创建表 $connection->createCommand()->createTable('post', [ 'id' => 'pk', 'title' => 'string', 'text' => 'text', ]);
完整参考请查看yii\db\Command.
SQL查询示例:
// find the customers whose primary key value is 10 $customers = Customer::findAll(10); $customer = Customer::findOne(10); // the above code is equivalent to: $customers = Customer::find()->where(['id' => 10])->all(); // find the customers whose primary key value is 10, 11 or 12. $customers = Customer::findAll([10, 11, 12]); $customers = Customer::find()->where(['IN','id',[10,11,12]])->all(); // the above code is equivalent to: $customers = Customer::find()->where(['id' => [10, 11, 12]])->all(); // find customers whose age is 30 and whose status is 1 $customers = Customer::findAll(['age' => 30, 'status' => 1]); // the above code is equivalent to: $customers = Customer::find()->where(['age' => 30, 'status' => 1])->all(); // use params binding $customers = Customer::find()->where('age=:age AND status=:status')->addParams([':age'=>30,':status'=>1])->all(); // use index $customers = Customer::find()->indexBy('id')->where(['age' => 30, 'status' => 1])->all(); // get customers count $count = Customer::find()->where(['age' => 30, 'status' => 1])->count(); // add addition condition $customers = Customer::find()->where(['age' => 30, 'status' => 1])->andWhere('score > 100')->orderBy('id DESC')->offset(5)->limit(10)->all(); // find by sql $customers = Customer::findBySql('SELECT * FROM customer WHERE age=30 AND status=1 AND score>100 ORDER BY id DESC LIMIT 5,10')->all();
修改:
// update status for customer-10 $customer = Customer::findOne(10); $customer->status = 1; $customer->update(); // the above code is equivalent to: Customer::updateAll(['status' => 1], 'id = :id',[':id'=>10]);
删除:
// delete customer-10 Customer::findOne(10)->delete(); // the above code is equivalent to: Customer::deleteAll(['status' => 1], 'id = :id',[':id'=>10]);
--------------------------------使用子查询------------------------------------------
$subQuery = (new Query())->select('COUNT(*)')->from('customer'); // SELECT `id`, (SELECT COUNT(*) FROM `customer`) AS `count` FROM `customer` $query = (new Query())->select(['id', 'count' => $subQuery])->from('customer');
--------------------------------手写SQL-------------------------------------------
// select $customers = Yii::$app->db->createCommand('SELECT * FROM customer')->queryAll(); // update Yii::$app->db->createCommand()->update('customer',['status'=>1],'id=10')->execute(); // delete Yii::$app->db->createCommand()->delete('customer','id=10')->execute(); //transaction // outer $transaction1 = $connection->beginTransaction(); try { $connection->createCommand($sql1)->execute(); // internal $transaction2 = $connection->beginTransaction(); try { $connection->createCommand($sql2)->execute(); $transaction2->commit(); } catch (Exception $e) { $transaction2->rollBack(); } $transaction1->commit(); } catch (Exception $e) { $transaction1->rollBack(); }
-----------------------------主从配置--------------------------------------------
[ 'class' => 'yii\db\Connection', // master 'dsn' => 'dsn for master server', 'username' => 'master', 'password' => '', // slaves 'slaveConfig' => [ 'username' => 'slave', 'password' => '', 'attributes' => [ // use a smaller connection timeout PDO::ATTR_TIMEOUT => 10, ], ], 'slaves' => [ ['dsn' => 'dsn for slave server 1'], ['dsn' => 'dsn for slave server 2'], ['dsn' => 'dsn for slave server 3'], ['dsn' => 'dsn for slave server 4'], ], ]