Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Unable to create a model with composite primary key

Hi,

I have three tables in Mysql DB.

  1. user: _id as PK
  2. role: _id as PK
  3. userrole: _id as AI userid FK to user roleid FK to role PRIMARY KEY(userid, role_id)

Models:

User

$this->hasMany('id', 'UserRole', 'userid', array('alias' => 'UserRole'));

Role

$this->hasMany('id', 'UserRole', 'roleid', array('alias' => 'UserRole'));

UserRole

  1. $this->belongsTo('roleid', 'Role', 'id', array('alias' => 'Role'));
  2. $this->belongsTo('userid', 'User', 'id', array('alias' => 'User'));
$model = new UserRole();
$model->user_id =1;
$model->role_id = 1;
$model->create();
/*
Which throws error:
Phalcon\Mvc\Model\Message Object
(
    [_type:protected] => InvalidCreateAttempt
    [_message:protected] => Record cannot be created because it already exists
    [_field:protected] => 
    [_model:protected] => 
)
*/

NOTE: user_role table is empty

Can any one plz suggest to overcome this error and how to define the relations in my above scenario.

thanks in advance.



99.5k
Accepted
answer
edited Jun '16

Phalcon just don't allow setting PKs. Just remove PK on user_id and role_id in database in user_role table and use uniquness validator.



684

thanks for the response. We have followed your suggestion and everything is fine now.