yii2: Unique validator doesn't prefix attribute name with model's database table name

Hi, this rule is in page model rules : [['code'], 'unique'] and code attribute exist in post model.

I join two table in page::find():

$query = new ActiveQuery(get_called_class()); $query->joinWith('post');

then ambiguous error accured on same code attribute.

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'code' in where clause is ambiguous 
The SQL being executed was: 
SELECT EXISTS(SELECT page.* FROM page LEFT JOIN post ON page.postId=post.id AND ((code='12')))

it seems in yii\validators\UniqueValidator::prepareConditions($targetAttribute, $model, $attribute) adding table name as prefix while preparing conditions solve this problem.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 25 (15 by maintainers)

Commits related to this issue

Most upvoted comments

Hi, what is the conclusion of this conversation?

I will check

I think the resolution of this Issue has caused a problem with query aliases. If someone overrides the find() method of the model and uses it to add and alias to the model table, the validator will execute a query that will cause an error.

Maybe the prefix used on the validator query should be extracted from the Query object and not from the tableName() method.