使用数据库之前我们必须通过在 config/main.php
添加「db」信息来配置数据库连接组件。
在 config
文件夹里创建一个数据库配置文件 db.php
,添加数据库配置信息,代码如下:
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=reportsa_macromoney', // 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' => '$123',
'charset' => 'utf8',
];
?>
现在我们要将此文件添加到配置 $config['components']['db']
参数数据库连接。示例如下(把下面的代码添加到 config/main.php
里):
'components' => [
'db'=>require(__DIR__ . '/db.php'),
.................
]
现在将创建数据库连接。 创建连接后,我们可以这样访问数据库的连接:
$connection = \Yii::$app->db;
$secondaryConnection = \Yii::$app->secondDb;