首页 文章

如何在Yii2中的ON条件中使用常量hasMany关系

提问于
浏览
21

我尝试创建一个多态关联,这在Rails中很常见,但遗憾的是在Yii2中没有 . 作为实现的一部分,我需要定义关系:

public function getImages()
{
   return $this->hasMany(RecipeImage::className(), 
       ['imageable_id' => 'id', 'imageable_type' => 'Person']);
}

但这不起作用,因为'Person'被视为当前模型的属性,但它是一个常量(多态关联的类名) .

如果我尝试使用'andWhere',它当然会在WHERE子句而不是ON子句中添加条件,导致只返回包含现有图像的记录 .

public function getImages()
{
   return $this->hasMany(RecipeImage::className(), ['imageable_id' => 'id'])->
       andWhere(['imageable_type' => 'Ingredient']);
}

我该如何定义关系?没有andOn方法 .

1 回答

  • 52

    在这种情况下,您可以使用 andOnCondition 方法修改ON条件:

    public function getImages()
    {
        return $this->hasMany(RecipeImage::className(), ['imageable_id' => 'id'])
            ->andOnCondition(['imageable_type' => 'Person']);
    }
    

    Official docs:

相关问题