Delete Function is throwing SQL Error

Hey it’s me again. :smiling_face:

I try to delete a user and get the following error.

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`cake_cms`.`articles`, CONSTRAINT `articles_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`))

I assume i can’t delete a USER without deleting also all depending ARTICLES also.
I think this dependency is written in the UsersTable.php but i dont know how i have to change it
to not get this error.

Thank you so much.

// UsersController.php
public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $user = $this->Users->get($id);

        $this->Authorization->authorize($user);

        if ($this->Users->delete($user)) {
            $this->Flash->success(__('The user has been deleted.'));
        } else {
            $this->Flash->error(__('The user could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }
// UsersTable.php
class UsersTable extends Table
{
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('users');
        $this->setDisplayField('email');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');

        $this->hasMany('Articles', [
            'foreignKey' => 'user_id',
        ]);
    }

since users and articles belong to each other (and are connected via a foreign key constraint in your table) you need to tell CakePHP, that they are “dependent”

See Deleting Data - 5.x

So you need

$this->hasMany('Articles', [
    'foreignKey' => 'user_id',
    'dependent' => true,
    'cascadeCallbacks' => true,
]);

so that all articles associated to a user are also deleted.

1 Like