Extension for CUniqueValidator

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;


				throw new CException(Yii::t('yii','Column "{column} does not exist in table "{table}".',


			else $customCriteria['params'][$k] = $object->$k;





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)



An alternative (cleaner?) fix


 * @var array a list of extra parameters to bind from the model


public $bindParams=array();

foreach($this->bindParams as $param)



		throw new CException(Yii::t('yii','Column "{column} does not exist in table "{table}".',



		'params' => array(':'.$param=> $object->$param)



There is a thread that has a related problem here.