Tib*_*agy 27 has-many relation polymorphic-associations yii2
我尝试创建一个多态关联,这在Rails中很常见,但遗憾的是在Yii2中没有.作为实现的一部分,我需要定义关系:
public function getImages()
{
return $this->hasMany(RecipeImage::className(),
['imageable_id' => 'id', 'imageable_type' => 'Person']);
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为'Person'被视为当前模型的属性,但它是一个常量(多态关联的类名).
如果我尝试使用'andWhere',它当然会在WHERE子句而不是ON子句中添加条件,导致只返回包含现有图像的记录.
public function getImages()
{
return $this->hasMany(RecipeImage::className(), ['imageable_id' => 'id'])->
andWhere(['imageable_type' => 'Ingredient']);
}
Run Code Online (Sandbox Code Playgroud)
我该如何定义关系?没有andOn方法.
aro*_*hev 60
在这种情况下,您可以使用andOnCondition方法修改ON条件:
public function getImages()
{
return $this->hasMany(RecipeImage::className(), ['imageable_id' => 'id'])
->andOnCondition(['imageable_type' => 'Person']);
}
Run Code Online (Sandbox Code Playgroud)
官方文档:
| 归档时间: |
|
| 查看次数: |
22634 次 |
| 最近记录: |