A
A
AlexKuznec2017-03-04 18:52:58
MySQL
AlexKuznec, 2017-03-04 18:52:58

Yii2 trigger error when trying to delete record?

I have 2 related tables in MySQL created via migrations: 'food' and 'import_log'. The latter has a trigger that prevents the associated entry from being removed from 'food':

// add foreign key for table `food`
        $this->addForeignKey(
            'fk-import_log-food_id',
            'import_log',
            'food_id',
            'food',
            'id',
            'RESTRICT'
        );

I don’t remember exactly, but earlier it seemed to give a normal message that the record could not be deleted.
Error now:
Caused by: PDOException
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`food`.`import_log`, CONSTRAINT `fk-import_log-food_id` FOREIGN KEY (`food_id`) REFERENCES `food` (`id`))
in C:\server\data\htdocs\site\vendor\yiisoft\yii2\db\Command.php at line 846
Is this how it should be, or am I - something messed up?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AlexKuznec, 2017-03-05
@AlexKuznec

As padlyuck suggested , Yii2 doesn't handle deletion triggers on its own, so I came up with this version of the deletion action:

public function actionDelete($id)
    {
        try {
            $this->findModel($id)->delete();
            Yii::$app->session->setFlash('success', Yii::t('app', 'controller.Food.deleted'));
        } catch (\Exception $e) {
            Yii::$app->session->setFlash('error', Yii::t('app', 'controller.Food.cannot_delete'));
        }
        
        return $this->redirect(['index']);
    }

P
padlyuck, 2017-03-04
@padlyuck

$this->addForeignKey(
'fk-import_log-food_id',
'import_log',
'food_id',
'food',
'id',
'SET NULL'
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question