We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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. user_role: _id as AI user_id FK to user role_id FK to role PRIMARY KEY(user_id, role_id)

Models:

User

$this->hasMany('_id', 'UserRole', 'user_id', array('alias' => 'UserRole'));

Role

$this->hasMany('_id', 'UserRole', 'role_id', array('alias' => 'UserRole'));

UserRole

  1. $this->belongsTo('role_id', 'Role', '_id', array('alias' => 'Role'));
  2. $this->belongsTo('user_id', '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.



145.0k
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.



2.5k

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