0

我想结合两个应用程序。其中之一作为模块。有两个不同的数据库。该模块使用另一个数据库作为基础应用程序。

我已经创建了 db 连接,它是 config.php 中的一个组件

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

我创建了一个 ModuleActiveRecord 类,它覆盖了 Active Record 函数 getDB():

class ModuleActiveRecord extends ActiveRecord
{
    public static function getDb()
    {
        $db = Yii::$app->controller->module->db;
        return Yii::createComponent($db);
}

我收到错误消息:该表不存在。任何人的想法?

4

2 回答 2

1

复制 db 连接文件并在 config (web.php) 中导入两个连接:

'components' => [
    ...
    'db' => require(__DIR__ . '/db.php'),
    'db_copy' => require(__DIR__ . '/db_copy.php'),
]

然后覆盖 ActiveRecord 中使用复制数据库的数据库连接,如下所示:

public static function getDb()
{
    return Yii::$app->get('db_copy');
}
于 2018-11-26T20:56:28.697 回答
1

您可以像其他答案一样添加多个数据库连接,例如:db/db_for_module。

您也可以像我一样配置模块(使用 Yii2 高级模板的示例):

// in common/config/main.php
[
    'db' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=test_db',
        'username' => 'root',
        'password' => '123456',    
        'charset' => 'utf8',
    ],
    'modules' => [
        'v1' => [
            'class' => \frontend\modules\v1\Module::class,
            // Increase the component configuration of the module
            'components' => [
                'db' => [
                    'class' => 'yii\db\Connection',
                    'dsn' => 'mysql:host=localhost;dbname=test_db_for_module',
                    'username' => 'root',
                    'password' => '111111',    
                    'charset' => 'utf8',
                ],
            ],
        ],
    ],
]

v1模块的定义

// in frontend/modules/Module.php
<?php

namespace frontend\modules\v1;

/**
 * v1 module definition class.
 */
class Module extends \yii\base\Module
{
    /**
     * {@inheritdoc}
     */
    public $controllerNamespace = 'frontend\modules\v1\controllers';
}

但是,您必须在模块代码中以特殊方式调用 db 组件,例如:

// in frontend/modules/v1/controllers/TestController.php
<?php

namespace frontend\modules\v1\controllers;

/**
 * Test Controller
 */
class TestController extends \yii\web\Controller {

    public function actionTest()
    {
        \Yii::$app->modules['v1']->db->createCommand(...); // This db points to the db connection of this module configuration
        // or
        $this->module->db->createCommand(...) // This db points to the db connection of this module configuration
    }
}

这样做的好处:

  • 您可以使用相同的名称:db(如果这是您所期望的,尽管它以特殊方式调用)
  • 此模块以外的代码看不到有关此数据库的配置。
  • 即使您没有此模块的特殊db连接,您仍然可以使用上述方法正确调用默认db连接(也许这不是您所期望的)
  • 可以清楚的表明这里使用了特殊的db连接配置

注意:这只是一种覆盖模块中应用程序默认组件的方法,以供参考。这个方法我没有实践过,但是我测试过这个是可行的。

于 2018-11-27T09:21:52.313 回答