Yii2关系在使用内部联接和jeft联接时重复

亚历克斯·米基汀

它们之间有3种关联的模型。

class A extends ActiveRecord
{
    public static function tableName(){
        return 'tbl_a';
    }
    public function getB()
    {
        return $this->hasOne(B::className(), ['column' => 'column']);
    }
}

class B extends ActiveRecord
{
    public static function tableName(){
        return 'tbl_b';
    }
    public function getC()
    {
        return $this->hasOne(C::className(), ['column' => 'column']);
    }
}

我有下一个代码:

$result = A::find()->joinWith('b')->where('');
if () {
    A->joinWith('b.c')->where('');
}
$result->createCommand()->rawSql;

结果我有下一个sql:

select * from tbl_a left join tbl_b on ... join tbl_b on ... join tbl_c on ... where ...

如您所见,sql查询重复表关系'tbl_b'。你知道为什么吗?

更新

好的,我更详细地研究了我的问题。如果使用不同的JOIN类型,则表连接是重复的。下一个原始模型:

class Myuser extends ActiveRecord
{
    public static function tableName(){
        return 'myuser';
    }

    public function getProfile()
    {
        return $this->hasOne(Profile::className(), ['user_id' => 'id']);
    }
}

class Profile extends \yii\db\ActiveRecord {

    public static function tableName(){
        return 'profile';
    }

    public function getCity()
    {
        return $this->hasOne(City::className(), ['id'=>'city_id']);
    }
}

执行的代码:

$get_city = 1;
$u = Myuser::find()->joinWith('profile', 0, 'INNER JOIN');
if ($get_city) {
    $u->joinWith('profile.city');
}
echo $u->createCommand()->rawSql;

结果:

SELECT `myuser`.* FROM `myuser` 
    INNER JOIN `profile` ON `myuser`.`id` = `profile`.`user_id`
    LEFT JOIN `profile` ON `myuser`.`id` = `profile`.`user_id`
    LEFT JOIN `city` ON `profile`.`city_id` = `city`.`id`

如果我需要获取唯一的表“配置文件”并从表“ city”中添加字段,该如何避免重复。如果表“ city”中没有字段,则值应为“ null”。

安东·里巴尔科(Anton Rybalko)

我想这是框架中的错误(或功能)。当您使用关系profile.city框架时,看不到已经由inner join...连接的关系。我假设如果您left join用于第一个关系,那么一切都会正常进行。

在您的情况下,尝试使用leftJoin()并指定联接的表名:

$get_city = 1;
$u = Myuser::find()->innerJoinWith('profile');
if ($get_city) {
    $u->leftJoin('city', 'profile.city_id = city.id');
}
echo $u->createCommand()->rawSql;

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章