68 lines
2.3 KiB
JavaScript
68 lines
2.3 KiB
JavaScript
const { Context, Vocab } = require('../models');
|
|
const { Op } = require('sequelize');
|
|
const { sequelize } = require('../config/database');
|
|
|
|
async function syncRefIdFromVocab() {
|
|
try {
|
|
await sequelize.authenticate();
|
|
console.log('✅ Kết nối database thành công.');
|
|
|
|
// 1. Tìm các bản ghi status = 5 và reference_id đang null hoặc trống
|
|
const contexts = await Context.findAll({
|
|
where: {
|
|
status: 5,
|
|
[Op.or]: [
|
|
{ reference_id: null },
|
|
{ reference_id: '' }
|
|
]
|
|
}
|
|
});
|
|
|
|
console.log(`📊 Tìm thấy ${contexts.length} bản ghi status = 5 thiếu reference_id.`);
|
|
|
|
let updatedCount = 0;
|
|
let notFoundCount = 0;
|
|
|
|
for (const context of contexts) {
|
|
// Tìm từ trong bảng Vocab có text khớp chính xác với title của Context
|
|
const vocab = await Vocab.findOne({
|
|
where: {
|
|
text: context.title
|
|
}
|
|
});
|
|
|
|
if (vocab) {
|
|
await context.update({ reference_id: vocab.vocab_id });
|
|
updatedCount++;
|
|
// console.log(`✅ ID ${context.uuid}: Đã khớp '${context.title}' -> Vocab ID ${vocab.vocab_id}`);
|
|
} else {
|
|
notFoundCount++;
|
|
console.log(`⚠️ ID ${context.uuid}: Không tìm thấy từ '${context.title}' trong bảng Vocab.`);
|
|
}
|
|
}
|
|
|
|
// 2. Kiểm tra lại số lượng còn sót sau khi update
|
|
const remainingCount = await Context.count({
|
|
where: {
|
|
status: 5,
|
|
[Op.or]: [
|
|
{ reference_id: null },
|
|
{ reference_id: '' }
|
|
]
|
|
}
|
|
});
|
|
|
|
console.log('\n--- KẾT QUẢ CẬP NHẬT REFERENCE_ID ---');
|
|
console.log(`✅ Đã cập nhật thành công: ${updatedCount} bản ghi.`);
|
|
console.log(`❌ Không tìm thấy Vocab khớp: ${notFoundCount} bản ghi.`);
|
|
console.log(`📊 Tổng số bản ghi status 5 vẫn còn thiếu reference_id: ${remainingCount}`);
|
|
|
|
process.exit(0);
|
|
} catch (error) {
|
|
console.error('❌ Lỗi khi migration:', error);
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
syncRefIdFromVocab();
|