From d6e57d85c1961b1d1b2ed432e9614f9622817c49 Mon Sep 17 00:00:00 2001 From: Atiwit Pattanapukdee <65160394@go.buu.ac.th> Date: Wed, 26 Mar 2025 17:04:08 +0700 Subject: [PATCH] Project Round 11 --- controllers/tourController.js | 14 +++++++++++-- models/tourModel.js | 38 +++++------------------------------ 2 files changed, 17 insertions(+), 35 deletions(-) diff --git a/controllers/tourController.js b/controllers/tourController.js index 248be51..55a53cd 100644 --- a/controllers/tourController.js +++ b/controllers/tourController.js @@ -253,13 +253,23 @@ exports.deleteTour = async (req, res) => { const tourId = req.params.id; console.log("Request to delete tour ID:", tourId); // ตรวจสอบค่า ID + // ตรวจสอบว่ามีการส่ง tourId มาหรือไม่ if (!tourId) { return res.status(400).send("Tour ID is required"); } - await Tour.deleteTour(tourId); - res.redirect('/'); + // ลบทัวร์ + const tour = await Tour.deleteTourById(tourId); + + // ตรวจสอบผลลัพธ์หลังจากการลบ + if (tour.affectedRows === 0) { + return res.status(404).send("Tour not found"); + } + + // Redirect ไปที่หน้าแรกหรือหน้าอื่น + res.redirect('/'); } catch (error) { + console.error("Error deleting tour:", error); res.status(500).send(error.message); } }; diff --git a/models/tourModel.js b/models/tourModel.js index 984cf05..3afa161 100644 --- a/models/tourModel.js +++ b/models/tourModel.js @@ -93,39 +93,11 @@ class Tour { } - // ลบทัวร์ - static async deleteTour(id) { - try { - console.log("Deleting tour with ID:", id); // เช็คค่า ID ที่รับมา - if (!id) { - throw new Error("Tour ID is required"); - } - - // ตรวจสอบว่าทัวร์มีอยู่จริง - const checkQuery = 'SELECT * FROM tours WHERE id = ?'; - const [tours] = await pool.execute(checkQuery, [id]); - - if (tours.length === 0) { - throw new Error("Tour not found"); - } - - // แจ้งเตือนก่อนลบ - const userConfirmation = confirm(`คุณต้องการลบทัวร์ "${tours[0].name}" หรือไม่?`); - if (!userConfirmation) { - throw new Error("ลบทัวร์ถูกยกเลิก"); - } - - // ลบข้อมูลทัวร์จากฐานข้อมูล - const deleteQuery = 'DELETE FROM tours WHERE id = ?'; - const [result] = await pool.execute(deleteQuery, [id]); - - console.log("Delete result:", result); - return result; - - } catch (error) { - console.error('Error deleting tour:', error); - throw new Error('เกิดข้อผิดพลาดในการลบทัวร์'); - } + // ลบทัวร์จากฐานข้อมูล + static async deleteTourById(id) { + const query = 'DELETE FROM tours WHERE id = ?'; + const [result] = await pool.execute(query, [id]); + return result; } -- GitLab