如何在 Yii2 的 ON 条件下使用常量 hasMany 关系 [英] How to use constant in the ON condition in Yii2 hasMany relation
问题描述
我尝试创建一个多态关联,这在 Rails 中很常见,但不幸的是在 Yii2 中没有.作为实现的一部分,我需要定义关系:
I try to create a polymorphic association, what is common in Rails but unfortunately not in Yii2. As part of the implementation I need to define the relation:
public function getImages()
{
return $this->hasMany(RecipeImage::className(),
['imageable_id' => 'id', 'imageable_type' => 'Person']);
}
但这不起作用,因为'Person'被视为当前模型的一个属性,但它是一个常量(多态关联的类名).
But this doesn't work, because 'Person' is treated as an attribute of the current model, but it is a constant (class name for the polymorphic association).
如果我尝试使用andWhere",它当然会在 WHERE 子句而不是 ON 子句中添加条件,导致仅返回具有现有图像的记录.
If I try to use 'andWhere' it adds the condition of course in a WHERE clause instead of the ON clause, causing that only records with existing image returned.
public function getImages()
{
return $this->hasMany(RecipeImage::className(), ['imageable_id' => 'id'])->
andWhere(['imageable_type' => 'Ingredient']);
}
如何定义关系?没有 andOn 方法.
How can I define the relation? There is no andOn method.
推荐答案
在这种情况下,您可以使用 andOnCondition
方法修改 ON 条件:
In this case you can modify ON condition with andOnCondition
method:
public function getImages()
{
return $this->hasMany(RecipeImage::className(), ['imageable_id' => 'id'])
->andOnCondition(['imageable_type' => 'Person']);
}
官方文档:
这篇关于如何在 Yii2 的 ON 条件下使用常量 hasMany 关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!