Issue
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);
}
Solution
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
]
);
Answered By - Fokrule
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.