I am going to show you an effective way to validate the uniqueness of multiple columns.
In the following example we have 3 columns, the combination of which need to be unique: id, category and language.
class Post extends CActiveRecord
{
public $oldId;
public $oldCategory;
public $oldLanguage;
public function rules()
{
return array(
array('id, category, language', 'required'),
array('id', 'checkUniqueness'),
);
}
public function checkUniqueness($attribute,$params)
{
if($this->id !== $this->oldId || $this->category !== $this->oldCategory || $this->language !== $this->oldLanguage)
{
$model = Post::model()->find('id = ? AND category = ? AND language = ?', array($this->id, $this->category, $this->language));
if($model != null)
$this->addError('id','This id, category and language already exist');
}
}
protected function afterFind()
{
parent::afterFind();
$this->oldId = $this->id;
$this->oldCategory = $this->category;
$this->oldLanguage = $this->language;
}
}
And that's all friends! Good luck!
Improvements
May I suggest some improvements?
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.