【问题标题】:How to use constant in the ON condition in Yii2 hasMany relationYii2 hasMany关系中如何在ON条件下使用常量
【发布时间】:2015-08-10 18:30:47
【问题描述】:

我尝试创建一个多态关联,这在 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 方法。

【问题讨论】:

    标签: yii2 has-many polymorphic-associations relation


    【解决方案1】:

    在这种情况下,您可以使用andOnCondition 方法修改 ON 条件:

    public function getImages()
    {
        return $this->hasMany(RecipeImage::className(), ['imageable_id' => 'id'])
            ->andOnCondition(['imageable_type' => 'Person']);
    }
    

    官方文档:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 2019-02-26
      • 1970-01-01
      • 1970-01-01
      • 2020-05-03
      • 2021-06-15
      • 1970-01-01
      相关资源
      最近更新 更多