Answer the question
In order to leave comments, you need to log in
Yii2 ActiveRecord How to JOIN tables between two mysql DB?
There are 2 models KladrCity and Area, each of them is in different DB both MYSQL.
In KladrCity
public static function getDb() {
return \Yii::$app->dbKladr;
}
public function getCity()
{
return $this->hasOne(KladrCity::className(), ['code' => 'city_id']);
}
$models = \common\models\Area::find()->joinWith('city');
Answer the question
In order to leave comments, you need to log in
JOIN
works inside your DB, it cannot make it to another database. In such cases, 2 requests are made, we select all the necessary areas - in php, as an example, we select through array_unique - only unique ones city_id
, we make a request to the database with city where in
(city ids) - we assign the array key to be city_id
, at any time we get the city for the area by type like this:$city[$area->city_id]
ActiveRecord
Yii doesn't do this on purpose, because it breaks compatibility with other types of databases where similar ones JOIN
don't work.
Developers advise to use with()
.
// find customers and bring back together their country and active orders
// SELECT * FROM `customer`
// SELECT * FROM `country` WHERE `id` IN (...)
// SELECT * FROM `order` WHERE `customer_id` IN (...) AND `status` = 1
$customers = Customer::find()->with([
'country',
'orders' => function ($query) {
$query->andWhere(['status' => Order::STATUS_ACTIVE]);
},
])->all();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question