Multiple Databases Connection on yii2

nodeffect picture nodeffect · May 26, 2015 · Viewed 9.1k times · Source

I'm trying to use multiple database connection on yii2 framework. Under my db.php file inside the config folder, I have this piece of code:

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

In my test.php under the models folder, I have this below...

namespace app\models;

use Yii;
use yii\base\Model;
use yii\db\Query;

class GetAds extends Model
{
    public function ads()
    {

        $test = Yii::$app->db1->createCommand((new \yii\db\Query)->select('*')->from('members'))->queryAll();

    }

when I try to access, I get this error message "Getting unknown property: yii\web\Application::db1"

How do I solve this problem ? I've actually followed this guide Multiple database connections and Yii 2.0

Where have I done wrong ?

The worst thing is, I've set to use just one database... and on my model, I use this code..

    namespace app\models;

    use Yii;
    use yii\base\Model;
    use yii\db\ActiveRecord;
    use yii\db\Query;

    class GetAds extends ActiveRecord
    {
        public static function tableName()
        {
            return 'ads_page';
        }

        public static function ads()
        {

            $count=(new \yii\db\Query)->from('ads_page')->count('*'); 
    }
}

And I get this error

Database Exception – yii\db\Exception
could not find driver
↵
Caused by: PDOException
could not find driver

Why is using yii2 so hard ? I've follow all from here http://www.yiiframework.com/doc-2.0/guide-db-dao.html

please help

Answer

nodeffect picture nodeffect · Jun 8, 2015

I've solved this problem. This might help others who need this.

Under config/web.php, I added this line "'db2' => require(__DIR__ . '/db2.php')," just under this statement "'db' => require(__DIR__ . '/db.php')," (without quotes)

and created another new db2.php file under the config folder using the same codes as in db.php:

<?php

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

and to call the first database. I use this:

$row = Yii::$app->db->createCommand("SELECT * FROM test")->queryOne(); 

To query table from the second database, I use this:

$row = Yii::$app->db2->createCommand("SELECT * FROM test2")->queryOne();