diff --git a/controllers/tourController.js b/controllers/tourController.js index e9325a9cd99cac4100f2f3fa582db6c2f3ab1221..48091bce056e6ad1f2aae7d847f94225dc047cb8 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 8f521245b605c86c55217cb500a6f330f64acafb..ff73644f3db13172e1abb61f7e45470e356a4279 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) {