Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

talentedaamer's avatar

Integrity constraint violation: 1451 Cannot delete or update a parent row

I have a results table with three foreign keys student_id, exam_id and grade_id. When I tried to delete the result it produced the above error.

Schema::create('results', function (Blueprint $table) {
            $table->increments('id');
            $table->bigInteger('student_id')->unsigned();
            $table->integer('exam_id')->unsigned();
            $table->integer('grade_id')->unsigned();
            $table->string('subject', 20);
            $table->integer('marks_obtained');
            $table->integer('marks_total');
            $table->decimal('percentage');
            $table->string('remarks')->nullable();
            $table->timestamps();
    
            $table->foreign('student_id')->references('id')->on('students');
            $table->foreign('exam_id')->references('id')->on('exams');
            $table->foreign('grade_id')->references('id')->on('grades');
        });

I came across with this solution to add onDelete('cascade') to every foreign key reference. My Question is if I delete result will it also delete the associated student, grade and exam?

is there a better solution for this? Please help. Thank you.

0 likes
2 replies
francois.levesque@live.ca's avatar

The onDelete('cascade') will delete the current row if the referenced row is deleted.

In your case, let's say you add onDelete('cascade') to student_id. You then add a result having student_id at 1. If you delete the student with the id 1, MySQL will automatically delete the result.

If the result doesn't make sense without an associated student, you should consider adding onDelete('cascade), it depends on what you are trying to acheive.

Regarding your error, is there a column where the results table is referenced?

1 like
talentedaamer's avatar

@chijipon thank you. I understood. It means I should only add onDelete('cascade') to student_id because I don't want a result to be deleted when grade or exam is deleted.

results table is not referenced to any other table. It only belongs to exam, grade and student

Full Error

"SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`database-name`.`results`, CONSTRAINT `results_grade_id_foreign` FOREIGN KEY (`grade_id`) REFERENCES `grades` (`id`)) (SQL: delete from `grades` where `id` = 4)

I get the same error if i try to delete a grade

"SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`database-name`.`results`, CONSTRAINT `results_grade_id_foreign` FOREIGN KEY (`grade_id`) REFERENCES `grades` (`id`)) (SQL: delete from `grades` where `id` = 0) "

Please or to participate in this conversation.