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.
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?
@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) "