我尝试创建一个多态关联,这在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 回答
在这种情况下,您可以使用
andOnCondition
方法修改ON条件:Official docs: