Fix exams foreign key constraint on lesson_id by using NULL instead of 0 for unit exams

This commit is contained in:
Hamza-Ayed
2026-09-03 16:46:17 +03:00
parent be4fe3dabf
commit 9624cfb4c8
2 changed files with 13 additions and 4 deletions
@@ -61,6 +61,15 @@ class AiQuestionBankGeneratorService
$aiQuestions = self::synthesizeQuestionsFromMarkdown($mdFiles, $targetCount);
}
// Ensure valid course_id exists in database
$courseCheck = Database::selectOne("SELECT id FROM courses WHERE id = ? LIMIT 1", [$courseId]);
if (!$courseCheck) {
$firstCourse = Database::selectOne("SELECT id FROM courses LIMIT 1");
if ($firstCourse) {
$courseId = (int)$firstCourse['id'];
}
}
// Ensure Unit Exam exists in database
$exam = Database::selectOne(
"SELECT id FROM exams WHERE course_id = ? AND (scope = 'unit_exam' OR scope = 'unit_comprehensive') AND (title LIKE ? OR title LIKE '%الوحدة الأولى%') LIMIT 1",
@@ -71,12 +80,12 @@ class AiQuestionBankGeneratorService
if (!$examId) {
$examId = (int)Database::insert(
"INSERT INTO exams (uuid, course_id, lesson_id, creator_type, scope, title, duration_minutes, passing_percentage, total_points, is_mandatory, is_published)
VALUES (UUID(), ?, 0, 'ai_adaptive', 'unit_exam', ?, 45, 70.00, 100, 1, 1)",
VALUES (UUID(), ?, NULL, 'ai_adaptive', 'unit_exam', ?, 45, 70.00, 100, 1, 1)",
[$courseId, "اختبار الفهم الشامل: {$unitTitle}"]
);
} else {
Database::query(
"UPDATE exams SET title = ?, duration_minutes = 45, scope = 'unit_exam', is_published = 1 WHERE id = ?",
"UPDATE exams SET title = ?, duration_minutes = 45, scope = 'unit_exam', lesson_id = NULL, is_published = 1 WHERE id = ?",
["اختبار الفهم الشامل: {$unitTitle}", $examId]
);
}