How to validate the uniqueness of multiple columns

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!

1 0
2 followers
Viewed: 8 274 times
Version: 1.1
Category: How-tos
Written by: oligalma
Last updated by: oligalma
Created on: Jan 15, 2015
Last updated: 2 years ago
Update Article

Revisions

View all history

Related Articles