106 lines
3.0 KiB
JavaScript
106 lines
3.0 KiB
JavaScript
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();
|