How to validate the uniqueness of multiple columns

You are viewing revision #9 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#10) »

I am going to show you an effective way to validate the uniqueness of multiple columns.

In the following example we have 3 columns 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()
        $this->oldId = $this->id;
        $this->oldCategory = $this->category;
        $this->oldLanguage = $this->language;

And that's all friends! Good luck!

1 0
Viewed: 12 472 times
Version: Unknown (update)
Category: How-tos
Written by: oligalma
Last updated by: oligalma
Created on: Jan 15, 2015
Last updated: 4 years ago
Update Article


View all history

Related Articles