Yii2 连接多个数据库
日常生活中我们一个项目一个数据库就足够了,但是难免会有意外,会使用多个数据库进行读写操作。例如:从另一个数据库导入数据到现在的数据库 今天就探讨下,Yii2.0
如何连接多个数据库
配置
打开数据库配置文件 common\config\main-local.php
,在原先的 db
配置项下面添加 db2
(可随意取名字),配置第二个数据库的属性
'components' => [
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=test',
'username' => '***',
'password' => '**',
'charset' => 'utf8',
],
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=test2',
'username' => '***',
'password' => '***',
'charset' => 'utf8',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
],
接下来就是模型的配置
namespace app\models;
use Yii;
/**
* This is the model class for table "test2".
*
* @property int $id
* @property string $name
*/
class Test2 extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'test2';
}
/**
* @return \yii\db\Connection the database connection used by this AR class.
*/
public static function getDb()
{
return Yii::$app->get('db2');
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['name'], 'string', 'max' => 60],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => '编号',
'name' => '姓名',
];
}
}
上面比我们普通的模型类仅仅多了一个 getDb
的方法而已
使用 Gii 更容易生成,直接设置 Database connection ID 为我们刚才配置的 db2 就好了
使用
使用方法还是和之前一样,你可以使用 ar
进行操作
Test::find()->all();
ok,这样我们的 Yii2
就可以连接多个数据库了,总结来说就是两步:配置数据库连接、新增 getDb
方法。
关于极客返利
极客返利 是由我个人开发的一款网课返利、返现平台。包含 极客时间返现、拉勾教育返现、掘金小册返现、GitChat返现。目前仅包含这几个平台。后续如果有需要可以考虑其他平台。 简而言之就是:你买课,我返现。让你花更少的钱,就可以买到课程。
版权许可
本作品采用 知识共享署名 4.0 国际许可协议 进行许可。转载无需与我联系,但须注明出处,注明文章来源 Yii2 连接多个数据库
联系我
