Quantcast
Channel: Live News for Yii Framework
Viewing all articles
Browse latest Browse all 2941

[Wiki] How to validate the uniqueness of multiple columns

$
0
0

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

In the following example we have 3 columns: 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', 'checkPost', 'on' => 'insert, update'),
        );
    }
 
    public function checkPost($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!


Viewing all articles
Browse latest Browse all 2941

Trending Articles