Hey people. Im using cakephp 3 and got the following problem.
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (prueba1
.operations_roles
, CONSTRAINT operations_roles_ibfk_2
FOREIGN KEY (role_id
) REFERENCES operations
(id
) ON DELETE CASCADE)
So basically what im doing is save a relationship belongstoMany between operations and roles for example.
This error happens when i create for example a role with “n” operations and then i delete.After delete the role i create another, that’s when the error is displayed . After deleting a relationship in operations_roles. Really i dont know why this happens.
Operations model
public function initialize(array $config)
{
parent::initialize($config);
$this->table('operations');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsToMany('Roles', [
'foreignKey' => 'operation_id',
'targetForeignKey' => 'role_id',
'joinTable' => 'operations_roles'
]);
}
Roles Model
public function initialize(array $config)
{
parent::initialize($config);
$this->table('roles');
$this->displayField('id');
$this->primaryKey('id');
$this->belongsToMany('Operations', [
'foreignKey' => 'role_id',
'targetForeignKey' => 'operation_id',
'joinTable' => 'operations_roles'
]);
}
my file migrations
$table = $this->table(‘roles’);
$table
->addColumn(‘rolname’,‘string’)
->addColumn(‘roldescripcion’,‘string’)
->create();
$table = $this->table('operations');
$table
->addColumn('opename','string')
->addColumn('opedescription','string')
->create();
$table = $this->table('operations_roles');
$table ->addColumn('operation_id','integer')->addForeignKey('operation_id','operations','id',array('delete'=>'CASCADE,'update' =>'CASCADE'))
->addColumn('role_id','integer')->addForeignKey('role_id','operations','id',array('delete'=>'CASCADE','update' =>'CASCADE'))
->create();
if anyone can help me , I would greatly appreciate it