我尝试创建一个多态关联,这在 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 方法。
在这种情况下,您可以使用以下命令修改 ON 条件andOnCondition
method:
public function getImages()
{
return $this->hasMany(RecipeImage::className(), ['imageable_id' => 'id'])
->andOnCondition(['imageable_type' => 'Person']);
}
官方文档:
- 和条件: http://www.yiiframework.com/doc-2.0/yii-db-activequery.html#andOnCondition%28%29-detail
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)