I have a table like this: (id, name, version, text). (name, version) is unique key, how can i make a rule to validate this.
Based on the function above, here is one function you can add onto your ActiveRecord Model
You would use it like so,
array( array('productname,productversion'), 'ValidateUniqueColumns', 'Product already contains that version'),
/*
* Validates the uniqueness of the attributes, multiple attributes
*/
public function ValidateUniqueColumns($attributes, $params)
{
$columns = explode(",", $attributes);
//Create the SQL Statement
$select_criteria = "";
$column_count = count($columns);
$lastcolumn = "";
for($index=0; $index<$column_count; $index++)
{
$lastcolumn = $columns[$index];
$value = Yii::app()->db->quoteValue( $this->getAttribute($columns[$index]) );
$column_equals = "`".$columns[$index]."` = ".$value."";
$select_criteria = $select_criteria.$column_equals;
$select_criteria = $select_criteria." ";
if($index + 1 < $column_count)
{
$select_criteria = $select_criteria." AND ";
}
}
$select_criteria = $select_criteria." AND `".$this->getTableSchema()->primaryKey."` <> ".Yii::app()->db->quoteValue($this->getAttribute( $this->getTableSchema()->primaryKey ))."";
$SQL = " SELECT COUNT(`".$this->getTableSchema()->primaryKey."`) AS COUNT_ FROM `".$this->tableName()."` WHERE ".$select_criteria;
$list = Yii::app()->db->createCommand($SQL)->queryAll();
$total = intval( $list[0]["COUNT_"] );
if($total > 0)
{
$this->addError($lastcolumn, $params[0]);
return false;
}
return true;
}