How to specify an alias for multiple join with one table?

I have two relationships defined in my model in the same table

public function getCountry(){
    return $this->hasOne(Country::className(),['country_id' => 'country_id']);
}

public function getCurrency(){
    return $this->hasOne(Country::className(), ['country_id' => 'currency']);
}

I want to join both relationships in my request. Below code shows the error.

Country::find()->joinWith(['country','currency'])->....

Tried it too

Country::find()->joinWith(['country','currency as cur'])->....

How to specify an alias for the second relationship

+4
source share
3 answers

You can specify an alias for a specific relationship, as shown below:

->joinWith([
    'country', 
    'currency' => function ($q) {
        $q->from(Country::tableName() . ' cur');
    }
])

Refer to this thread for more information - https://github.com/yiisoft/yii2/issues/2377#issuecomment-34573765

+5
source

Starting with Yii 2.0.7:

->joinWith(['country', 'currency cur'])... // Note we dont use 'as', just an space

Source: Yii2 Guide

+4
source

Category::find()
    ->select('c1.*')
    ->from('category c0')
    ->innerJoin('category as c1', 'c1.parent_id = c0.id')
    ->where(['c0.slug' => $parent]);
0

Source: https://habr.com/ru/post/1623075/


All Articles