Load related ORM of another database

Is there any way to load eager data “with” or ‘joinWith’ for ORM by another database ?

I use Yii 2.0.9

For example

$companies = Company::find()->joinWith('city')->all(); 

In model Company I have

public function getCity() {

        return $this->hasOne(\common\models\City::className(), ['id' => 'city_id']);


City is model has already configured to another database using:

 public static function getDb() {

        return Yii::$app->get('db_another_database');


But is not work, the generated query does not include the name of another_database.city_table.id in condition LEFT JOIN

so a database exception occurs

I tried

$companies = Company::find()->leftJoin('another_database.city_table AS city' , 'company.city_id=city.id')->all(); 

But although the generated query is corrected the data of city for each company loaded by lazy method

How to solve it ?


For your information the best way for this issue (in my opinion) is

$companies = Company::find()

            ->joinWith(['city' => function($query) { 

                   return $query->from('another_database.city_table')


Thanks Dmitry :)