sen
sen

Reputation: 129

YII2.0 query for multiple database

I have two database in my application,and both database all the tables are same(Except user table, first database only have a user table) via the first database i made login.

For example : database1.test and database2.test, i have created the test model with the help of first database test table.

After login based on the user_type i have connected the DB.

Code in user model:

public static function selectDb($user_type) {
        switch($user_type) {
            case 1:
                return Yii::$app->get('db2'); //database2
            case 0:
                return Yii::$app->get('db1'); //database1

        }
    }

so that now i make the connection with database2,and i write the query using test model

My query :

$model = \app\models\Test::find()->all();

empty result is showing in this query.

My Test model

class Test extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_test';
    }

    /**
     * @return \yii\db\Connection the database connection used by this AR class.
     */
    public static function getDb()
    {
        return Yii::$app->get('db1');
    }





    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
        ];
    }
}

May i know how to get solution for my problem.

Upvotes: 2

Views: 549

Answers (1)

Martijn Hols
Martijn Hols

Reputation: 1598

In your code sample your Test::getDb() always gets the first database, it doesn't take into account the $user_type and therefore doesn't use the selected database. Your User::selectDb() function returns the database you want to use but it doesn't alter any global state which would make it the default (and it shouldn't).

To fix your issue, the Test::getDb() method will have to be able to find the database selected by User::selectDb().

If you're using a custom user account class that implements the IdentityInterface (docs), as I suspect you are, then you could add a method there like so to your User class;

/**
* @returns \yii\db\Connection
*/
public function getSelectedDb()
{
    return static::selectDb($this->user_type);
}

and then your Test class could look like the following:

/**
 * @return \yii\db\Connection gets a connection to the database for the current user type.
 */
public static function getDb()
{
    /** @var app\models\User */
    $user = Yii::$app->user;
    return $user->getSelectedDb();
}

You might want to extend on this last piece of code to ensure it also works if $user is null (e.g. return $user ? $user->getSelectedDb() : Yii::$app->get('db1')). This can happen if the user isn't logged in.

Upvotes: 0

Related Questions