Reputation: 91
I am using multiple database connection in my system(Yii 2). db and db2, db2 connection is from another database server.
Its run smoothly when im use it normally(in controller). but when i am using it in commands i got this error
i have this in my code
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;
}
Upvotes: 0
Views: 699
Reputation: 3567
You need to add db2.php to console.php as well. That is the config that is loaded during console commands (as you can se here).
Upvotes: 3