如何为同一个表指定多个连接的别名?

ck_*_*jun 5 yii2

我的模型中有两个关系定义在同一个表中

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

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

我想在我的查询中加入这两个关系.下面的代码显示错误.

Country::find()->joinWith(['country','currency'])->....
Run Code Online (Sandbox Code Playgroud)

也试过这个

Country::find()->joinWith(['country','currency as cur'])->....
Run Code Online (Sandbox Code Playgroud)

如何为第二关系指定别名?

sdl*_*ins 9

从 Yii 2.0.7 开始:

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

资料来源:Yii2 指南


小智 5

您可以为特定关系提供别名,如下所示:

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

请参阅此主题以获取更多详细信息 - https://github.com/yiisoft/yii2/issues/2377#issuecomment-34573765