Search code examples
phpkohanakohana-3kohana-orm

Kohana 3.1 ORM: How to implement a "unique" validation rule?


does exists a "unique" validation rule (if does, how to implement it?) or must be implemented via callback? Thanks.


Solution

  • ) As far as I know there is no universal "unique" (or "is_unique") rule of Validation class. That's probably because of not regular nature of this kind of check.

    However, if you would like do it nicely, you could create a 'base model' for all your models you use in your application (make them extend the base one). Then, the uniqueness could be checked more or less like this:

    public function is_unique($id)
    {
        return ! (bool) DB::select(array(DB::expr('COUNT(id)'), 'total'))
            ->from($this->_table_name)
            ->where('id', '=', $id)
            ->execute()
            ->get('total');
    }
    

    In your validation rules you have to add this rule:

    array('id' => array(array(array($this, 'is_unique')));
    

    I have internal model rules stored in the method rules(), as recommended. So this could be a live example:

    class Model_Base_Model extends ORM
    {
        public function rules()
        {
            return array(
                'id' => array(
                    array(array($this, 'is_unique')),
                );
        }
    
    
        public function is_unique($id)
        {
            return ! (bool) DB::select(array(DB::expr('COUNT(id)'), 'total'))
                ->from($this->_table_name)
                ->where('id', '=', $id)
                ->execute()
                ->get('total');
        }
    }
    

    Now every model extending the Model_Base_Model will be now able to check it's uniqueness while creating. Hope this helps! :)