Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify alias for multiple join with same table?

Tags:

yii2

I have two relations defined in my Model to 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 relation in my query. Below code is showing error.

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

Tried this too

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

How to specify alias for the second relation ??

like image 718
ck_arjun Avatar asked Jan 06 '16 11:01

ck_arjun


3 Answers

Since Yii 2.0.7:

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

Source: Yii2 Guide

like image 187
sdlins Avatar answered Dec 08 '22 17:12

sdlins


You can give alias to particular relation as below :

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

Refer this thread to get further details - https://github.com/yiisoft/yii2/issues/2377#issuecomment-34573765

like image 36
Karmraj Zala Avatar answered Dec 08 '22 18:12

Karmraj Zala


without relations

Category::find()
    ->select('c1.*')
    ->from('category c0')
    ->innerJoin('category as c1', 'c1.parent_id = c0.id')
    ->where(['c0.slug' => $parent]);
like image 30
tannerman Avatar answered Dec 08 '22 18:12

tannerman