1

I am using cakePHP 3. I am trying to delete data from a table. But this data have relation with another table as foreign key. If the data id is not present on another table then data delete successfully. But problem is if the data id is available on another table then it shows error. error is like SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails ('project'.'post', CONSTRAINTpost_ibfk_1FOREIGN KEY (user_id) REFERENCESusers(id)). Suppose I have user table. And post table. Now post table have a column named user_id. Now when I try to delete an user and if this user id is not present in post table as foreign key, then it delete without any error. But if the user id is present in post table and I try to delete user then it shows me error. Here is mt delete button code

 <?php
     echo $this->Html->link(
        __($this->Html->tag('i','', array('class' => 'fa fa-trash text- 
        inverse m-r-10'))),                                              
     ['controller'=>'User', 'action' => 'deleteUser', $user->id],
      ['escape' => false,'data-toggle' => 'tooltip', 'data-original-title' => 'Delete']);?>

Here is my controller delete function

public function deleteUser($id)
{
    $user= $this->User->get($id);
    $this->User->delete($user);
}
Jignesh Mistry
  • 2,221
  • 6
  • 25
  • 50
Fokrule
  • 844
  • 2
  • 11
  • 30
  • 1
    Having the exact wording of the error message (rather than "something like this") is very helpful in determining exactly where the error is coming from. My best guess here would be that your database schema has constraints that prevent deletion of a record referenced by other records. If that's the case, and the constraint is legitimate, then you'd want to delete the other records first, a goal that can be accomplished with [cascading deletes](https://book.cakephp.org/3.0/en/orm/deleting-data.html#cascading-deletes). – Greg Schmidt Jul 10 '18 at 03:39
  • Thank you for your suggestion. I have updated my question with actual error message. – Fokrule Jul 10 '18 at 03:43

1 Answers1

4

I have found the solution cakephp 3.x cascade delete not working.

I have just added those code in my UsersTable.php

$this->hasMany(
        'post', [
            'foreignKey' => 'user_id', 
            'dependent'  => true,
            'cascadeCallbacks' => true
        ]
    );
Fokrule
  • 844
  • 2
  • 11
  • 30