How to use constant in the ON condition in Yii2 hasMany relation

隐身守侯 提交于 2019-12-22 01:13:27

问题


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']);
}

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).

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']);
}

How can I define the relation? There is no andOn method.


回答1:


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']);
}

Official docs:

  • andOnCondition:


来源:https://stackoverflow.com/questions/30503341/how-to-use-constant-in-the-on-condition-in-yii2-hasmany-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!