From 95e3e5d43198754ffba4ace6cf01cea19f161a4f Mon Sep 17 00:00:00 2001 From: Atiwit Pattanapukdee <65160394@go.buu.ac.th> Date: Tue, 18 Mar 2025 23:36:14 +0700 Subject: [PATCH] Project Round 6 --- controllers/tourController.js | 10 ++-------- models/tourModel.js | 20 +++++++++----------- 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/controllers/tourController.js b/controllers/tourController.js index e9325a9..48091bc 100644 --- a/controllers/tourController.js +++ b/controllers/tourController.js @@ -209,19 +209,13 @@ exports.postCreateTour = async (req, res) => { } }; -// ค้นหาทัวร์ +//ค้นหาทัวร์ exports.searchTours = async (req, res) => { try { const searchQuery = req.query.query; const tours = await Tour.searchTours(searchQuery); - - // หากไม่พบทัวร์จากการค้นหา - if (tours.length === 0) { - return res.render('search', { tours: [], message: 'ไม่พบที่ค้นหา' }); - } - res.render('search', { tours, session: req.session }); } catch (error) { res.status(500).send("Error searching tours"); } -}; +}; \ No newline at end of file diff --git a/models/tourModel.js b/models/tourModel.js index 8f52124..ff73644 100644 --- a/models/tourModel.js +++ b/models/tourModel.js @@ -14,23 +14,21 @@ class Tour { } } - static async searchTours(req, res) { - const query = req.query.query; + // ค้นหาทัวร์โดยใช้ชื่อ + static async searchTours(query) { try { - const tours = await Tour.searchTours(query); - - // ถ้าไม่มีทัวร์ในผลลัพธ์ - if (tours.length === 0) { - console.log('ไม่พบทัวร์ที่ค้นหา'); + + const [rows] = await pool.query('SELECT * FROM tours WHERE name LIKE ?', [`%${query}%`]); + // หากไม่มีทัวร์ที่ตรงกับคำค้นหา + if (rows.length === 0) { + return 'ไม่พบทัวร์ที่ตรงกับคำค้นหาของคุณ'; } - - res.render('search', { tours }); + return rows; } catch (error) { console.error('Error searching tours:', error.message); - res.render('search', { tours: [] }); + throw new Error('เกิดข้อผิดพลาดในการค้นหาทัวร์'); } } - // สร้างทัวร์ static async createTour(name, description, price, duration) { -- GitLab