How to validate the uniqueness of multiple columns

You are viewing revision #10 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#9)

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!

2 0
2 followers
Viewed: 18 363 times
Version: Unknown (update)
Category: How-tos
Written by: oligalma
Last updated by: oligalma
Created on: Jan 15, 2015
Last updated: 8 years ago
Update Article

Revisions

View all history

Related Articles