Gitlab@Informatics

Skip to content
Snippets Groups Projects
tourModel.js 5.50 KiB
const pool = require('../config/database');
const bcrypt = require('bcryptjs');
class Tour {
    // ดึงทัวร์ทั้งหมด
    static async getAllTours(userId) {
      try {
        console.log('Fetching all tours');
        
        // ดึงทัวร์ทั้งหมดที่ userId ตรงกับผู้ใช้ที่ล็อกอิน
        const [rows] = await pool.query('SELECT * FROM tours');
    
        console.log('Tours fetched successfully:', rows);
        return rows;
      } catch (error) {
        console.error('Error fetching tours:', error.message);
        throw new Error('เกิดข้อผิดพลาดในการดึงข้อมูลทัวร์: ' + error.message);
      }
    }
    
    // ค้นหาทัวร์โดยใช้ชื่อ
    static async searchTours(query) {
      try {

        const [rows] = await pool.query('SELECT * FROM tours WHERE name LIKE ?', [`%${query}%`]);
        // หากไม่มีทัวร์ที่ตรงกับคำค้นหา
        if (rows.length === 0) {
          return 'ไม่พบทัวร์ที่ตรงกับคำค้นหาของคุณ';
        }
        return rows;
      } catch (error) {
        console.error('Error searching tours:', error.message);
        throw new Error('เกิดข้อผิดพลาดในการค้นหาทัวร์');
      }
    }

    // สร้างทัวร์
    static async createTour(name, description, price, duration, userId, companyid) {
      // ตรวจสอบข้อมูล
      if (!name || !price || !duration || !companyid) {
        throw new Error('ข้อมูลไม่ครบถ้วน กรุณากรอกข้อมูลให้ครบถ้วน');
      }
    
      const query = 'INSERT INTO tours (name, description, price, duration, userId, companyid) VALUES (?, ?, ?, ?, ?, ?)';
      try {
        // บันทึกทัวร์พร้อมกับ userId ที่สร้างทัวร์
        await pool.execute(query, [name, description, price, duration, userId, companyid]);
      } catch (error) {
        console.error('Error creating tour:', error);
        throw new Error('เกิดข้อผิดพลาดในการสร้างทัวร์');
      }
    }
    
  
    // อัปเดตทัวร์
    static async updateTour(tourId, tourData) {
      const { name, description, price, duration, companyid } = tourData;
    
      // ตรวจสอบข้อมูลให้ครบถ้วน
      if (!name || !description || !price || !duration|| !companyid) {
        throw new Error('ข้อมูลไม่ครบถ้วน');
      }
    
      // สร้างคำสั่ง SQL สำหรับการอัปเดตข้อมูล
      const query = 'UPDATE tours SET name = ?, description = ?, price = ?, duration = ? , companyid = ? WHERE id = ?';
      
      try {
        // ใช้ tourId ที่รับมาในการอัปเดต
        const [results] = await pool.execute(query, [name, description, price, duration, companyid, tourId]);
        console.log('✅ Update results:', results);
        return results;