数据库访问 (DAO)
Yii 包含了一个建立在 PHP PDO 之上的数据访问层 (DAO). DAO为不同的数据库提供了一套统一的API. 其中`
ActiveRecord`
提供了数据库与模型(MVC 中的 M,Model) 的交互,`
QueryBuilder`
用于创建动态的查询语句. DAO提供了简单高效的SQL查询,可以用在与数据库交互的各个地方.
Yii 默认支持以下数据库 (DBMS):
- MySQL
- MariaDB
- SQLite
- PostgreSQL
- CUBRID: 版本 >= 9.3 . (由于PHP PDO 扩展的一个bug 引用值会无效,所以你需要在 CUBRID的客户端和服务端都使用 9.3 )
- Oracle
- MSSQL: 版本>=2005.
配置
开始使用数据库首先需要配置数据库连接组件,通过添加 db 组件到应用配置实现("基础的" Web 应用是 config/web.php),DSN( Data Source Name )是数据源名称,用于指定数据库信息.如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > return </span> [
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'components' </span> => [
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'db' </span> => [
<span style= "box-sizing: border-box;" > 'class' </span> => <span style= "box-sizing: border-box;" > 'yii\db\Connection' </span>,
<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > 'mysql:host=localhost;dbname=mydatabase' </span>, <span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'username' </span> => <span style= "box-sizing: border-box;" > 'root' </span>, <span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'password' </span> => <span style= "box-sizing: border-box;" > '' </span>, <span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'charset' </span> => <span style= "box-sizing: border-box;" > 'utf8' </span>,
],
],
<span style= "box-sizing: border-box;" >
];
</code>
|
请参考PHP manual获取更多有关 DSN 格式信息。 配置连接组件后可以使用以下语法访问:
$connection = \Yii::$app->db;
请参考yii\db\Connection
获取可配置的属性列表。 如果你想通过ODBC连接数据库,则需要配置yii\db\Connection::driverName 属性,例如:
1 2 3 4 5 6 7 8 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > 'db' </span> => [
<span style= "box-sizing: border-box;" > 'class' </span> => <span style= "box-sizing: border-box;" > 'yii\db\Connection' </span>,
<span style= "box-sizing: border-box;" > 'driverName' </span> => <span style= "box-sizing: border-box;" > 'mysql' </span>,
<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > 'odbc:Driver={MySQL};Server=localhost;Database=test' </span>,
<span style= "box-sizing: border-box;" > 'username' </span> => <span style= "box-sizing: border-box;" > 'root' </span>,
<span style= "box-sizing: border-box;" > 'password' </span> => <span style= "box-sizing: border-box;" > '' </span>,
],
</code>
|
注意:如果需要同时使用多个数据库可以定义 多个 连接组件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > return </span> [
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'components' </span> => [
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'db' </span> => [
<span style= "box-sizing: border-box;" > 'class' </span> => <span style= "box-sizing: border-box;" > 'yii\db\Connection' </span>,
<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > 'mysql:host=localhost;dbname=mydatabase' </span>,
<span style= "box-sizing: border-box;" > 'username' </span> => <span style= "box-sizing: border-box;" > 'root' </span>,
<span style= "box-sizing: border-box;" > 'password' </span> => <span style= "box-sizing: border-box;" > '' </span>,
<span style= "box-sizing: border-box;" > 'charset' </span> => <span style= "box-sizing: border-box;" > 'utf8' </span>,
],
<span style= "box-sizing: border-box;" > 'secondDb' </span> => [
<span style= "box-sizing: border-box;" > 'class' </span> => <span style= "box-sizing: border-box;" > 'yii\db\Connection' </span>,
<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > 'sqlite:/path/to/database/file' </span>,
],
],
<span style= "box-sizing: border-box;" >
];
</code>
|
在代码中通过以下方式使用:
1 2 3 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $primaryConnection </span> = \Yii::<span style= "box-sizing: border-box;" > $app -</span>>db;
<span style= "box-sizing: border-box;" > $secondaryConnection </span> = \Yii::<span style= "box-sizing: border-box;" > $app -</span>>secondDb;
</code>
|
如果不想定义数据库连接为全局应用组件,可以在代码中直接初始化使用:
1 2 3 4 5 6 7 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $connection </span> = new \yii\db\Connection([
<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > $dsn </span>,
<span style= "box-sizing: border-box;" > 'username' </span> => <span style= "box-sizing: border-box;" > $username </span>,
<span style= "box-sizing: border-box;" > 'password' </span> => <span style= "box-sizing: border-box;" > $password </span>,
]);
<span style= "box-sizing: border-box;" > $connection -</span>>open();
</code>
|
>小提示:如果在创建了连接后需要执行额外的 SQL 查询,可以添加以下代码到应用配置文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > return </span> [
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'components' </span> => [
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'db' </span> => [
<span style= "box-sizing: border-box;" > 'class' </span> => <span style= "box-sizing: border-box;" > 'yii\db\Connection' </span>,
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'on afterOpen' </span> => <span style= "box-sizing: border-box;" ><span style= "box-sizing: border-box;" > function </span><span style= "box-sizing: border-box;" >(<span style= "box-sizing: border-box;" > $event </span>)</span> </span>{
<span style= "box-sizing: border-box;" > $event </span>->sender->createCommand(<span style= "box-sizing: border-box;" > "SET time_zone = 'UTC'" </span>)->execute();
}
],
],
<span style= "box-sizing: border-box;" >
];
</code>
|
SQL 基础查询
一旦有了连接实例就可以通过yii\db\Command执行 SQL 查询。
SELECT 查询
查询返回多行:
1 2 3 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $command </span> = <span style= "box-sizing: border-box;" > $connection -</span>>createCommand(<span style= "box-sizing: border-box;" > 'SELECT * FROM post' </span>);
<span style= "box-sizing: border-box;" > $posts </span> = <span style= "box-sizing: border-box;" > $command -</span>>queryAll();
</code>
|
返回单行:
1 2 3 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $command </span> = <span style= "box-sizing: border-box;" > $connection -</span>>createCommand(<span style= "box-sizing: border-box;" > 'SELECT * FROM post WHERE id=1' </span>);
<span style= "box-sizing: border-box;" > $post </span> = <span style= "box-sizing: border-box;" > $command -</span>>queryOne();
</code>
|
查询多行单值:
1 2 3 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $command </span> = <span style= "box-sizing: border-box;" > $connection -</span>>createCommand(<span style= "box-sizing: border-box;" > 'SELECT title FROM post' </span>);
<span style= "box-sizing: border-box;" > $titles </span> = <span style= "box-sizing: border-box;" > $command -</span>>queryColumn();
</code>
|
查询标量值/计算值:
1 2 3 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $command </span> = <span style= "box-sizing: border-box;" > $connection -</span>>createCommand(<span style= "box-sizing: border-box;" > 'SELECT COUNT(*) FROM post' </span>);
<span style= "box-sizing: border-box;" > $postCount </span> = <span style= "box-sizing: border-box;" > $command -</span>>queryScalar();
</code>
|
UPDATE, INSERT, DELETE 更新、插入和删除等
如果执行 SQL 不返回任何数据可使用命令中的 execute 方法:
1 2 3 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $command </span> = <span style= "box-sizing: border-box;" > $connection -</span>>createCommand(<span style= "box-sizing: border-box;" > 'UPDATE post SET status=1 WHERE id=1' </span>);
<span style= "box-sizing: border-box;" > $command -</span>>execute();
</code>
|
你可以使用insert
,update
,delete
方法,这些方法会根据参数生成合适的SQL并执行.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'name' </span> => <span style= "box-sizing: border-box;" > 'Sam' </span>,
<span style= "box-sizing: border-box;" > 'age' </span> => <span style= "box-sizing: border-box;" >30</span>,
])->execute();
<span style= "box-sizing: border-box;" >
[<span style= "box-sizing: border-box;" > 'Tom' </span>, <span style= "box-sizing: border-box;" >30</span>],
[<span style= "box-sizing: border-box;" > 'Jane' </span>, <span style= "box-sizing: border-box;" >20</span>],
[<span style= "box-sizing: border-box;" > 'Linda' </span>, <span style= "box-sizing: border-box;" >25</span>],
])->execute();
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" >
</code>
|
引用的表名和列名
大多数时间都使用以下语法来安全地引用表名和列名:
1 2 3 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $sql </span> = <span style= "box-sizing: border-box;" > "SELECT COUNT($column) FROM {{table}}" </span>;
<span style= "box-sizing: border-box;" > $rowCount </span> = <span style= "box-sizing: border-box;" > $connection </span>->createCommand(<span style= "box-sizing: border-box;" > $sql </span>)->queryScalar();
</code>
|
以上代码$column
会转变为引用恰当的列名,而{{table}}
就转变为引用恰当的表名。 表名有个特殊的变量 {{%Y}} ,如果设置了表前缀使用该变体可以自动在表名前添加前缀:
1 2 3 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $sql </span> = <span style= "box-sizing: border-box;" > "SELECT COUNT($column) FROM {{%$table}}" </span>;
<span style= "box-sizing: border-box;" > $rowCount </span> = <span style= "box-sizing: border-box;" > $connection </span>->createCommand(<span style= "box-sizing: border-box;" > $sql </span>)->queryScalar();
</code>
|
如果在配置文件如下设置了表前缀,以上代码将在 tbl_table 这个表查询结果:
1 2 3 4 5 6 7 8 9 10 11 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > return </span> [
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'components' </span> => [
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'db' </span> => [
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'tablePrefix' </span> => <span style= "box-sizing: border-box;" > 'tbl_' </span>,
],
],
];
</code>
|
手工引用表名和列名的另一个选择是使用yii\db\Connection::quoteTableName() 和 yii\db\Connection::quoteColumnName():
1 2 3 4 5 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $column </span> = <span style= "box-sizing: border-box;" > $connection </span>->quoteColumnName(<span style= "box-sizing: border-box;" > $column </span>);
<span style= "box-sizing: border-box;" > $table </span> = <span style= "box-sizing: border-box;" > $connection </span>->quoteTableName(<span style= "box-sizing: border-box;" > $table </span>);
<span style= "box-sizing: border-box;" > $sql </span> = <span style= "box-sizing: border-box;" > "SELECT COUNT($column) FROM $table" </span>;
<span style= "box-sizing: border-box;" > $rowCount </span> = <span style= "box-sizing: border-box;" > $connection </span>->createCommand(<span style= "box-sizing: border-box;" > $sql </span>)->queryScalar();
</code>
|
预处理语句
为安全传递查询参数可以使用预处理语句,首先应当使用:placeholder
占位,再将变量绑定到对应占位符:
1 2 3 4 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $command </span> = <span style= "box-sizing: border-box;" > $connection </span>->createCommand(<span style= "box-sizing: border-box;" > 'SELECT * FROM post WHERE id=:id' </span>);
<span style= "box-sizing: border-box;" > $command </span>->bindValue(<span style= "box-sizing: border-box;" > ':id' </span>, <span style= "box-sizing: border-box;" > $_GET </span>[<span style= "box-sizing: border-box;" > 'id' </span>]);
<span style= "box-sizing: border-box;" > $post </span> = <span style= "box-sizing: border-box;" > $command </span>->query();
</code>
|
另一种用法是准备一次预处理语句而执行多次查询:
1 2 3 4 5 6 7 8 9 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $command </span> = <span style= "box-sizing: border-box;" > $connection </span>->createCommand(<span style= "box-sizing: border-box;" > 'DELETE FROM post WHERE id=:id' </span>);
<span style= "box-sizing: border-box;" > $command </span>->bindParam(<span style= "box-sizing: border-box;" > ':id' </span>, <span style= "box-sizing: border-box;" > $id </span>);
<span style= "box-sizing: border-box;" > $id </span> = <span style= "box-sizing: border-box;" >1</span>;
<span style= "box-sizing: border-box;" > $command </span>->execute();
<span style= "box-sizing: border-box;" > $id </span> = <span style= "box-sizing: border-box;" >2</span>;
<span style= "box-sizing: border-box;" > $command </span>->execute();
</code>
|
>提示,在执行前绑定变量,然后在每个执行中改变变量的值(一般用在循环中)比较高效.
事务
当你需要顺序执行多个相关的的query
时,你可以把他们封装到一个事务中去保护数据一致性.Yii提供了一个简单的接口来实现事务操作. 如下执行 SQL 事务查询语句:
1 2 3 4 5 6 7 8 9 10 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $transaction </span> = <span style= "box-sizing: border-box;" > $connection </span>->beginTransaction();
<span style= "box-sizing: border-box;" > try </span> {
<span style= "box-sizing: border-box;" > $connection </span>->createCommand(<span style= "box-sizing: border-box;" > $sql1 </span>)->execute();
<span style= "box-sizing: border-box;" > $connection </span>->createCommand(<span style= "box-sizing: border-box;" > $sql2 </span>)->execute();
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > $transaction </span>->commit();
} <span style= "box-sizing: border-box;" > catch </span>(<span style= "box-sizing: border-box;" >Exception</span> <span style= "box-sizing: border-box;" > $e </span>) {
<span style= "box-sizing: border-box;" > $transaction </span>->rollBack();
}
</code>
|
我们通过yii\db\Connection::beginTransaction()开始一个事务,通过try catch
捕获异常.当执行成功,通过yii\db\Transaction::commit()提交事务并结束,当发生异常失败通过yii\db\Transaction::rollBack()进行事务回滚.
如需要也可以嵌套多个事务:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > try </span> {
<span style= "box-sizing: border-box;" > $connection </span>->createCommand(<span style= "box-sizing: border-box;" > $sql1 </span>)->execute();
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > $transaction2 </span> = <span style= "box-sizing: border-box;" > $connection </span>->beginTransaction();
<span style= "box-sizing: border-box;" > try </span> {
<span style= "box-sizing: border-box;" > $connection </span>->createCommand(<span style= "box-sizing: border-box;" > $sql2 </span>)->execute();
<span style= "box-sizing: border-box;" > $transaction2 </span>->commit();
} <span style= "box-sizing: border-box;" > catch </span> (<span style= "box-sizing: border-box;" >Exception</span> <span style= "box-sizing: border-box;" > $e </span>) {
<span style= "box-sizing: border-box;" > $transaction2 </span>->rollBack();
}
<span style= "box-sizing: border-box;" > $transaction1 </span>->commit();
} <span style= "box-sizing: border-box;" > catch </span> (<span style= "box-sizing: border-box;" >Exception</span> <span style= "box-sizing: border-box;" > $e </span>) {
<span style= "box-sizing: border-box;" > $transaction1 </span>->rollBack();
}
</code>
|
>注意你使用的数据库必须支持Savepoints
才能正确地执行,以上代码在所有关系数据中都可以执行,但是只有支持Savepoints
才能保证安全性。
Yii 也支持为事务设置隔离级别isolation levels
,当执行事务时会使用数据库默认的隔离级别,你也可以为事物指定隔离级别. Yii 提供了以下常量作为常用的隔离级别
- \yii\db\Transaction::READ_UNCOMMITTED - 允许读取改变了的还未提交的数据,可能导致脏读、不可重复读和幻读
- \yii\db\Transaction::READ_COMMITTED - 允许并发事务提交之后读取,可以避免脏读,可能导致重复读和幻读。
- \yii\db\Transaction::REPEATABLE_READ - 对相同字段的多次读取结果一致,可导致幻读。
- \yii\db\Transaction::SERIALIZABLE - 完全服从ACID的原则,确保不发生脏读、不可重复读和幻读。
你可以使用以上常量或者使用一个string字符串命令,在对应数据库中执行该命令用以设置隔离级别,比如对于postgres
有效的命令为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
数据库复制和读写分离
很多数据库支持数据库复制 database replication来提高可用性和响应速度. 在数据库复制中,数据总是从主服务器 到 从服务器. 所有的插入和更新等写操作在主服务器执行,而读操作在从服务器执行.
通过配置yii\db\Connection可以实现数据库复制和读写分离.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" >[
<span style= "box-sizing: border-box;" > 'class' </span> => <span style= "box-sizing: border-box;" > 'yii\db\Connection' </span>,
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > 'dsn for master server' </span>,
<span style= "box-sizing: border-box;" > 'username' </span> => <span style= "box-sizing: border-box;" > 'master' </span>,
<span style= "box-sizing: border-box;" > 'password' </span> => <span style= "box-sizing: border-box;" > '' </span>,
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'slaveConfig' </span> => [
<span style= "box-sizing: border-box;" > 'username' </span> => <span style= "box-sizing: border-box;" > 'slave' </span>,
<span style= "box-sizing: border-box;" > 'password' </span> => <span style= "box-sizing: border-box;" > '' </span>,
<span style= "box-sizing: border-box;" > 'attributes' </span> => [
<span style= "box-sizing: border-box;" >
PDO::ATTR_TIMEOUT => <span style= "box-sizing: border-box;" >10</span>,
],
],
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'slaves' </span> => [
[<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > 'dsn for slave server 1' </span>],
[<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > 'dsn for slave server 2' </span>],
[<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > 'dsn for slave server 3' </span>],
[<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > 'dsn for slave server 4' </span>],
],
]
</code>
|
以上的配置实现了一主多从的结构,从服务器用以执行读查询,主服务器执行写入查询,读写分离的功能由后台代码自动完成.调用者无须关心.例如:
1 2 3 4 5 6 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" >
</code>
|
>注意:通过yii\db\Command::execute() 执行的查询被认为是写操作,所有使用yii\db\Command来执行的其他查询方法被认为是读操作.你可以通过$db->slave
得到当前正在使用能够的从服务器.
Connection
组件支持从服务器的负载均衡和故障转移,当第一次执行读查询时,会随即选择一个从服务器进行连接,如果连接失败则又选择另一个,如果所有从服务器都不可用,则会连接主服务器。你可以配置yii\db\Connection::serverStatusCache来记住那些不能连接的从服务器,使Yii 在一段时间[[yii\db\Connection::serverRetryInterval].内不会重复尝试连接那些根本不可用的从服务器.
>注意:在上述配置中,每个从服务器连接超时时间被指定为10s. 如果在10s内不能连接,则被认为该服务器已经挂掉.你也可以自定义超时参数.
你也可以配置多主多从的结构,例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" >[
<span style= "box-sizing: border-box;" > 'class' </span> => <span style= "box-sizing: border-box;" > 'yii\db\Connection' </span>,
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'masterConfig' </span> => [
<span style= "box-sizing: border-box;" > 'username' </span> => <span style= "box-sizing: border-box;" > 'master' </span>,
<span style= "box-sizing: border-box;" > 'password' </span> => <span style= "box-sizing: border-box;" > '' </span>,
<span style= "box-sizing: border-box;" > 'attributes' </span> => [
<span style= "box-sizing: border-box;" >
PDO::ATTR_TIMEOUT => <span style= "box-sizing: border-box;" >10</span>,
],
],
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'masters' </span> => [
[<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > 'dsn for master server 1' </span>],
[<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > 'dsn for master server 2' </span>],
],
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'slaveConfig' </span> => [
<span style= "box-sizing: border-box;" > 'username' </span> => <span style= "box-sizing: border-box;" > 'slave' </span>,
<span style= "box-sizing: border-box;" > 'password' </span> => <span style= "box-sizing: border-box;" > '' </span>,
<span style= "box-sizing: border-box;" > 'attributes' </span> => [
<span style= "box-sizing: border-box;" >
PDO::ATTR_TIMEOUT => <span style= "box-sizing: border-box;" >10</span>,
],
],
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'slaves' </span> => [
[<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > 'dsn for slave server 1' </span>],
[<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > 'dsn for slave server 2' </span>],
[<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > 'dsn for slave server 3' </span>],
[<span style= "box-sizing: border-box;" > 'dsn' </span> => <span style= "box-sizing: border-box;" > 'dsn for slave server 4' </span>],
],
]
</code>
|
上述配置制定了2个主服务器和4个从服务器.Connection
组件也支持主服务器的负载均衡和故障转移,与从服务器不同的是,如果所有主服务器都不可用,则会抛出异常.
>注意:当你使用yii\db\Connection::masters来配置一个或多个主服务器时,Connection
中关于数据库连接的其他属性(例如:dsn
,username
, password
)都会被忽略.
事务默认使用主服务器的连接,并且在事务执行中的所有操作都会使用主服务器的连接,例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > try </span> {
<span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > $rows </span> = <span style= "box-sizing: border-box;" > $db </span>->createCommand(<span style= "box-sizing: border-box;" > 'SELECT * FROM user LIMIT 10' </span>)->queryAll();
<span style= "box-sizing: border-box;" > $db </span>->createCommand(<span style= "box-sizing: border-box;" > "UPDATE user SET username='demo' WHERE id=1" </span>)->execute();
<span style= "box-sizing: border-box;" > $transaction </span>->commit();
} <span style= "box-sizing: border-box;" > catch </span>(\<span style= "box-sizing: border-box;" >Exception</span> <span style= "box-sizing: border-box;" > $e </span>) {
<span style= "box-sizing: border-box;" > $transaction </span>->rollBack();
<span style= "box-sizing: border-box;" > throw </span> <span style= "box-sizing: border-box;" > $e </span>;
}
</code>
|
如果你想在从服务器上执行事务操作则必须要明确地指定,比如:
1 2 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $transaction </span> = <span style= "box-sizing: border-box;" > $db </span>->slave->beginTransaction();
</code>
|
有时你想强制使用主服务器来执行读查询,你可以调用seMaster()
方法.
1 2 3 4 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $rows </span> = <span style= "box-sizing: border-box;" > $db </span>->useMaster(<span style= "box-sizing: border-box;" ><span style= "box-sizing: border-box;" > function </span> <span style= "box-sizing: border-box;" >(<span style= "box-sizing: border-box;" > $db </span>)</span> </span>{
<span style= "box-sizing: border-box;" > return </span> <span style= "box-sizing: border-box;" > $db </span>->createCommand(<span style= "box-sizing: border-box;" > 'SELECT * FROM user LIMIT 10' </span>)->queryAll();
});
</code>
|
你也可以设置$db->enableSlaves
为false
来使所有查询都在主服务器上执行.
操作数据库模式
获得模式信息
你可以通过 yii\db\Schema实例来获取Schema信息:
1 2 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $schema </span> = <span style= "box-sizing: border-box;" > $connection </span>->getSchema();
</code>
|
该实例包括一系列方法来检索数据库多方面的信息:
1 2 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" > $tables </span> = <span style= "box-sizing: border-box;" > $schema </span>->getTableNames();
</code>
|
更多信息请参考yii\db\Schema
修改模式
除了基础的 SQL 查询,yii\db\Command还包括一系列方法来修改数据库模式:
- 创建/重命名/删除/清空表
- 增加/重命名/删除/修改字段
- 增加/删除主键
- 增加/删除外键
- 创建/删除索引
使用示例:
1 2 3 4 5 6 | <code style= "box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: inherit; padding: 0px; color: inherit; border-radius: 0px; white-space: pre-wrap; background-color: transparent;" ><span style= "box-sizing: border-box;" >
<span style= "box-sizing: border-box;" > 'id' </span> => <span style= "box-sizing: border-box;" > 'pk' </span>,
<span style= "box-sizing: border-box;" > 'title' </span> => <span style= "box-sizing: border-box;" > 'string' </span>,
<span style= "box-sizing: border-box;" > 'text' </span> => <span style= "box-sizing: border-box;" > 'text' </span>,
]);
</code>
|