Hi guys,
I was working on the following problem: I wanted an attribute to be unique in a table, but only within a group of th e same id’s.
Example: in a table (id, foreign_key, name), name should be unique within a group of rows with the same foreign key.
I didn’t really find a clean way to do it, so I ‘hacked’ it into CUniqueValidator like this.
if($this->criteria!==array()) {
$customCriteria = $this->criteria;
if(isset($customCriteria['params'])) {
foreach($customCriteria['params'] as $k => $v) {
if($v != null) continue;
if(($column=$table->getColumn($k))===null)
throw new CException(Yii::t('yii','Column "{column} does not exist in table "{table}".',
array('{column}'=>$k,'{table}'=>$table->name)));
else $customCriteria['params'][$k] = $object->$k;
}
}
$criteria->mergeWith($customCriteria);
}
and you use it by putting something like this in your Model:
array('name', 'unique', 'criteria' => array(
'condition' => 'foreign_key = :foreign_key',
'params' => array('foreign_key' => null)
)),
So what do you think? Anyone with a better idea on how to handle this?
If possible I’d like to see something like this in a future Yii release (I prefer to have my local copy not to differ too much from the official release)
Thanks,
Javache