This commit is contained in:
67
migration_scripts/sync-ref-id-from-sentences.js
Normal file
67
migration_scripts/sync-ref-id-from-sentences.js
Normal file
@@ -0,0 +1,67 @@
|
||||
const { Context, Sentences } = require('../models');
|
||||
const { Op } = require('sequelize');
|
||||
const { sequelize } = require('../config/database');
|
||||
|
||||
async function syncRefIdFromSentences() {
|
||||
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 câu trong bảng Sentences có text khớp chính xác với title của Context
|
||||
const sentence = await Sentences.findOne({
|
||||
where: {
|
||||
text: context.title
|
||||
}
|
||||
});
|
||||
|
||||
if (sentence) {
|
||||
await context.update({ reference_id: sentence.id });
|
||||
updatedCount++;
|
||||
// console.log(`✅ ID ${context.uuid}: Đã khớp '${context.title}' -> Sentence ID ${sentence.id}`);
|
||||
} else {
|
||||
notFoundCount++;
|
||||
// console.log(`⚠️ ID ${context.uuid}: Không tìm thấy câu '${context.title}' trong bảng Sentences.`);
|
||||
}
|
||||
}
|
||||
|
||||
// 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 TỪ SENTENCES ---');
|
||||
console.log(`✅ Đã cập nhật thành công: ${updatedCount} bản ghi.`);
|
||||
console.log(`❌ Không tìm thấy Sentence 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);
|
||||
}
|
||||
}
|
||||
|
||||
syncRefIdFromSentences();
|
||||
Reference in New Issue
Block a user