Yii2应用程序将数据从一个数据库分发到使用特定字段过滤的不同数据库

时间:2017-04-19 04:08:05

标签: database yii2

我想做一个模块,根据特定的属性将我的应用程序的数据分发到不同的数据库。

假设我当前的程序收集员工信息,这里是我的字段:

db_company

  tbl_employee => [id, fname, mname, lname, name_suffix, birthdate, address, sex, civil_status]

现在我想根据一个特定字段分发数据,这些字段是不同数据库中具有相同表结构的civil_status。

db_company_single

  tbl_employee => [id, fname, mname, lname, name_suffix, birthdate, address, sex, civil_status]

db_company_married

  tbl_employee => [id, fname, mname, lname, name_suffix, birthdate, address, sex, civil_status]

是否可以仅使用模块?

谢谢。

3 个答案:

答案 0 :(得分:1)

您必须覆盖模型中的getDb(),并根据静态变量更改它返回的连接。

<强>配置:

'db' => [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=db_company_single',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
],
'dbMarried' => [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=db_company_married',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8',
],

<强>控制器:

$model = new Employee();
// Already false but it's easier to get the idea.
Employee::$isMarried = false;

$model->fname = 'Single';
$model->save();

Employee::$isMarried = true;

$model->fname = 'Married';
$model->save();

<强>型号:

public static $isMarried = false;

public static function getDb() {
    if (self::$isMarried === true) {
        return Yii::$app->dbMarried;
    } else {
        return Yii::$app->db;
    }
}

答案 1 :(得分:0)

是的,您需要切换database个连接。

答案 2 :(得分:0)

对于您的情况,您可能需要使用主从配置,并将其他数据库连接与从配置相关联,Yii2文档在此处对其进行了描述Yii2 Master Slave

示例代码

  [
    'class' => 'yii\db\Connection',

    // configuration for the master
    'dsn' => 'dsn for master server',
    'username' => 'master',
    'password' => '',

    // common configuration for slaves
    'slaveConfig' => [
        'username' => 'slave',
        'password' => '',
        'attributes' => [
            // use a smaller connection timeout
            PDO::ATTR_TIMEOUT => 10,
        ],
    ],

    // list of slave configurations
    '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'],
    ],
]