const { sequelize } = require('../config/database'); const { StudentDetail, UserProfile, UsersAuth, setupRelationships } = require('../models'); async function testJoin() { try { await sequelize.authenticate(); console.log('āœ… Connected to database'); // Setup relationships BEFORE querying setupRelationships(); console.log('āœ… Relationships initialized\n'); // Test 1: Raw SQL query console.log('šŸ“Š Test 1: Raw SQL Join'); const [rawResults] = await sequelize.query(` SELECT sd.id, sd.user_id, sd.student_code, up.id as profile_id, up.user_id as profile_user_id, up.full_name FROM student_details sd LEFT JOIN user_profiles up ON sd.user_id = up.user_id WHERE sd.student_code LIKE 'pri_apdinh%' LIMIT 3 `); console.log('Raw SQL Results:'); rawResults.forEach(row => { console.log({ student_id: row.id, student_user_id: row.user_id, student_code: row.student_code, profile_id: row.profile_id, profile_user_id: row.profile_user_id, full_name: row.full_name, join_works: row.profile_id ? 'āœ… YES' : 'āŒ NO' }); }); // Test 2: Sequelize query console.log('\nšŸ“Š Test 2: Sequelize Join'); const students = await StudentDetail.findAll({ where: sequelize.where( sequelize.fn('LOWER', sequelize.col('student_code')), 'LIKE', 'pri_apdinh%' ), include: [{ model: UserProfile, as: 'profile', required: false, }], limit: 3 }); console.log('Sequelize Results:'); students.forEach(student => { console.log({ student_id: student.id, student_user_id: student.user_id, student_code: student.student_code, profile: student.profile ? { id: student.profile.id, user_id: student.profile.user_id, full_name: student.profile.full_name, join_works: 'āœ… YES' } : 'āŒ NO PROFILE' }); }); // Test 3: Check data integrity console.log('\nšŸ“Š Test 3: Data Integrity Check'); const sampleStudent = await StudentDetail.findOne({ where: sequelize.where( sequelize.fn('LOWER', sequelize.col('student_code')), 'LIKE', 'pri_apdinh%' ) }); if (sampleStudent) { console.log(`Student user_id: ${sampleStudent.user_id}`); const matchingProfile = await UserProfile.findOne({ where: { user_id: sampleStudent.user_id } }); if (matchingProfile) { console.log(`āœ… Found matching profile: ${matchingProfile.full_name}`); console.log(`Profile user_id: ${matchingProfile.user_id}`); } else { console.log(`āŒ No matching profile found for user_id: ${sampleStudent.user_id}`); } } } catch (error) { console.error('āŒ Error:', error); } finally { await sequelize.close(); } } testJoin();