本文介绍了如何在Yii2的ON条件下使用常数hasMany关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建一个多态关联,这在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关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:15