Question

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

Was it helpful?

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! :)

OTHER TIPS

In Kohana 3.2 ORM has a unique() method that does the check, I'm not sure if it exists in 3.1, but it should.

With that you can just add a rule to your model like this:

array(array($this, 'unique'), array('some_field', ':value')),

and it will check if some_field is unique

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top