Yii 1.1: 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()
        $this->oldId = $this->id;
        $this->oldCategory = $this->category;
        $this->oldLanguage = $this->language;

And that's all friends! Good luck!

Total 1 comment

#18943 report it
le_top at 2015/02/08 06:20pm

May I suggest some improvements? - A find may be more effective than a count (because of the limit 1), but you may consider limiting the select to the primary key; - You need 'oldId', ... - you may consider excluding the record corresponding to the current primary id from the search which avoids keeping the 'old'*, and only in case the record is not a 'isNewRecord()' of course. - Also, this does not validate that each column value is unique, but that the combination of the column values is unique. - Finally, defining a unique index on the three columns (done when you create the table/do a migration of course) will further optimize execution and avoid any potential case where this setup may not work (for instance, when updating a single field like category through an update() and updateAll() for example ).

Leave a comment

Please to leave your comment.

Write new article