setting relation to different database server based on a field

Dear All,

I really appreciate the multiple database connection in yii 2. It is really helping in the integration of servers apps.

My current situation is, I have an Invoice table in master database (server is 192.168.1.101). In addition, the Customer table that is also reside in the same database, master database. Relation is easily defined using




    /**

     * @return \yii\db\ActiveQuery

     */

    public function getCustomer() {

        return $this->hasOne(Customer::className(), ['id' => 'customerFk']);

    }



Since, I also integrate the system with simiar system for a certain development block, I need to connect to Customer table in block database (server address 192.168.1.102). Both Customer table in both server have same structure. Only the data is different.

I can easily connect to the Customer in 102 server using




    /**

     * @return \yii\db\ActiveQuery

     */

    public function getBCustomer() {

        return $this->hasOne(blockI\Customer::className(), ['id' => 'partnerFk']);

    }



In Invoice, I will differentiate 101 and 102 Cusomer database according to serverType field in Incoice table.

Is it possible to create just one relation and us serverType attribute in Incoide as the decider? Can someone help with the code?

Thank you for your help.

I wrote this Wiki article a few years ago so YMMV, but it might give you an idea on how to switch database connections. Look at the part where it describes "protected/components/AppStartup.php" and find how to apply it to Yii2. Good luck.