YII2在2个数据库的表之间的模型中创建关系

时间:2016-04-05 06:46:53

标签: yii2 relationship yii2-advanced-app multiple-databases yii2-model

我已定义了2个数据库,例如

return [
'components' => [
    'db1' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=db1name', 
        'username' => 'db1username',
        'password' => 'db1password',
    ],
    'db2' => [
        'class' => 'yii\db\Connection',
        'dsn' => 'mysql:host=localhost;dbname=db2name', 
        'username' => 'db2username',
        'password' => 'db2password',
    ],
],
];

现在我有一张桌子作为'用户' in' db1'和表'国家'在' db2'

users 
id , country_code , username , password
1  , DE           , xyz      , 12345
2  , FR           , abc      , 12345

countries
code , name
DE   , Germany
FR   , France
IN   , India

我已经定义了users.country_code和amp;之间的外键关系。 countries.code

问题

但是,当我尝试为“用户”创建模型时,'使用gii的表它会产生错误,可能是因为表关系来自2个不同的数据库。 如何在模型的关系中使用来自不同数据库的表。

欢迎任何建议

2 个答案:

答案 0 :(得分:0)

在我的情况下,这可以在GridView :: widget上列出它

-> bd_sisarc is my secound data base
-> deposito_sondagem is a table from my first data base


public static function getDb()   // on your model
{
    return Yii::$app->get('db1');
}

public static function getDb()   // on your model
{
    return Yii::$app->get('db2');
}

public function getEmpresaSondagem()  // Relation on you model
{
    return $this->hasOne(EmpresaSondagem::className(), ['idEmpSondagem' => 'entidade_deposito']);
}





public function search($params)
{


    $this->load($params);

    $sql = "SELECT deposito_sondagem.*
                  FROM
                      deposito_sondagem,
                      `bd_sisarc`.`tbempresasondagem`
                  WHERE
                      `bd_sisarc`.`tbempresasondagem`.`idEmpSondagem`=`deposito_sondagem`.`entidade_deposito`

                      and deposito_sondagem.estado=1
                      and tbempresasondagem.estado=1
                      and numero_registo LIKE '%$this->numero_registo%'
                      and nomeempsondagem LIKE '%$this->nomeEntidade%'
                      and dono_sondagem LIKE '%$this->dono_sondagem%'
                      and data_deposito LIKE '%$this->data_deposito%'";


    $query = DepositoSondagem::findBySql($sql);
    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);


    if (!$this->validate()) {
        // uncomment the following line if you do not want to return any records when validation fails
        // $query->where('0=1');
        return $dataProvider;
    }


    return $dataProvider;
}

答案 1 :(得分:-1)

试试这个

SELECT `users`.* FROM `users` LEFT JOIN `db2name`.`countries` ON `users`.`country_code` = `db2name`.`countries`.`code `