在yii2中使用命令时无法使用多个数据库

时间:2019-02-26 23:55:35

标签: php yii2 multiple-databases

我在系统中使用多个数据库连接(Yii 2)。 db和db2,db2连接来自另一个数据库服务器。

当我正常使用它时(在控制器中)它运行平稳。但是当我在命令中使用它时,出现此错误

enter image description here

我的代码中有这个

web.php

 $db = require __DIR__ . '/db.php';
 $db2 = require __DIR__ . '/db2.php';

    'components' => [
    'db' => $db,
            'db2' => $db2,
],

db.php

<?php

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

    // Schema cache options (for production environment)
    'enableSchemaCache' => true,
    'schemaCacheDuration' => 60,
    'schemaCache' => 'cache',
];

db2.php

<?php

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=10.50.0.161;dbname=xxx',
    'username' => 'xxx',
    'password' => 'xxxx',
    'charset' => 'utf8',

    // Schema cache options (for production environment)
    'enableSchemaCache' => true,
    'schemaCacheDuration' => 60,
    'schemaCache' => 'cache',
];

Tblprcobiodata.php

class Tblprcobiodata extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface {

    // add the function below:
    public static function getDb() {
        return Yii::$app->get('db2'); // second database
    }

commands / KehadiranController.php

public function actionTest() {
    $biodata = Tblprcobiodata::findAll(['DeptId' => 137]);


    foreach ($biodata as $bio) {
        echo $bio->CONm . '-' . TblRekod::totalSalah($bio->ICNO, 02);
    }

    return ExitCode::OK;
}

1 个答案:

答案 0 :(得分:3)

您还需要将db2.php添加到console.php。这就是在控制台命令期间加载的配置(如您所here所示)。