我在系统中使用多个数据库连接(Yii 2)。 db和db2,db2连接来自另一个数据库服务器。
当我正常使用它时(在控制器中)它运行平稳。但是当我在命令中使用它时,出现此错误
我的代码中有这个
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;
}