Search code examples
phpmysqlormkohanakohana-3.2

Kohana 3.2 validate composite primary key


I have following table

create table `groupusers`(
 `id` int not null auto_increment,
 `user` varchar(100) not null,
 `group` varchar(100) not null,
 UNIQUE KEY(`id`),
 PRIMARY KEY(`user`, `group`)
)

My model looks like this,

class Model_Groupuser extends ORM{
    protected $_table_name = 'groupusers';

    public function rules(){
        return array(
                'user' => array(
                        array('not_empty'),
                        array(array($this, 'user_group_not_exists')),
                ),
                'group' => array(
                        array('not_empty'),
                        array(array($this, 'user_group_not_exists')),
                )
        );
    }

    public function user_group_not_exists($param){
        // Need to get other field's value here.
    }
}

Problem is every time user_group_not_exists is called, its called with a single parameter. Either user or group. But I need both to determine if the combination exists in the db already.

How can I get current model's fields' value?


Solution

  • You can get other fields value using $this->object() function.

    public function user_group_not_exists($user_or_group){
        $obj = $this->object();
        $group = $obj['group'];
        $user = $obj['user'];
    
        // Check if ($group, $user) pair exists in db here
    }