0

例如,我定义了 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',
    ],
],
];

现在我在'db1'中有一个表作为'users',在'db2'中有一个表'countries'

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 & countries.code 之间的外键关系

问题

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

欢迎任何建议

4

2 回答 2

0

在我的情况下,这适用于在 GridView::widget 上列出iten

-> 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;
}
于 2019-09-12T11:26:27.913 回答
-2

Try this one

SELECT `users`.* FROM `users` LEFT JOIN `db2name`.`countries` ON `users`.`country_code` = `db2name`.`countries`.`code `
于 2016-11-23T12:42:39.950 回答