英文:
Why is Sequelize giving UnknownConstraintError and dropping the tables?
问题
I am working on an app where I am using MySQL database and Sequelize on Node backend. I have created some models with complex relationships. For eg: There are Chat and Message model that help in implementing chatting functionality. But whenever I start my application I get this error: UnknownConstraintError [SequelizeUnknownConstraintError]: Constraint Message_ibfk_2 on table Message does not exist. Sometimes it is for Chat table, here it is for Message. I know something is wrong in the way I am defining the relationships but don't know what exactly. I had looked at many answers while designing the relationships. At that time, the through tables and foreign keys were not getting added so some suggested to use await Chat.sync/ await sequelize.sync to design these relationships. I don't know if this is causing the error or what but any help is much appreciated.
const sequelize = require('../config/sequelize');
const {DataTypes} = require('sequelize');
const User = require('./User');
let Chat = sequelize.define('Chat',{
name:{
type:DataTypes.STRING,
allowNull:false
},
isGroupChat:{
type:DataTypes.BOOLEAN,
defaultValue:false
},
},{freezeTableName:true});
(async function(){
Chat.belongsToMany(User,{through:'ChatUser'});
User belongsToMany(Chat,{through:'ChatUser'});
Chat.belongsTo(User,{
foreignKey:'groupAdmin',
as:'admin'
});
await sequelize.sync({alter:true});
})();
module.exports = Chat;
const sequelize = require('../config/sequelize');
const {DataTypes} = require('sequelize');
const Chat = require('./Chats');
const User = require('./User')
let Message = sequelize.define('Message',{
content:{
type:DataTypes.TEXT,
allowNull:false
},
},{freezeTableName:true});
(async function(){
Message.belongsTo(User,{
foreignKey:'sender'
})
Message.belongsTo(Chat,{
foreignKey:'chat_id'
})
Chat.belongsTo(Message,{as:'lastMessage',foreignKey:'latest_message',targetKey:'id'})
await sequelize.sync({alter:true});
})();
module.exports = Message;
const User = require('./models/User');
const Chat = require('./models/Chats');
const Message = require('./models/Messages');
(async function(){
try{
await sequelize.authenticate();
console.log('//// connection successful');
await sequelize.sync({alter:true});
}catch(err){
console.log('!!!! Error in connecting to DB',err);
}
})();
英文:
I am working on an app where I am using MySQL database and Sequelize on Node backend. I have created some models with complex relationships. For eg: There are Chat and Message model that help in implementing chatting functionality. But whenever I start my application I get this error: UnknownConstraintError [SequelizeUnknownConstraintError]: Constraint Message_ibfk_2 on table Message does not exist. Sometimes it is for Chat table, here it is for Message. I know something is wrong in the way I am defining the relationships but don't know what exactly. I had looked at many answers while designing the relationships. At that time, the through tables and foreign keys were not getting added so some suggested to use await Chat.sync/ await sequelize.sync to design these relationships. I don't know if this is causing the error or what but any help is much appreciated
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
const sequelize = require('../config/sequelize');
const {DataTypes} = require('sequelize');
const User = require('./User');
let Chat = sequelize.define('Chat',{
name:{
type:DataTypes.STRING,
allowNull:false
},
isGroupChat:{
type:DataTypes.BOOLEAN,
defaultValue:false
},
},{freezeTableName:true});
(async function(){
Chat.belongsToMany(User,{through:'ChatUser'});
User.belongsToMany(Chat,{through:'ChatUser'});
Chat.belongsTo(User,{
foreignKey:'groupAdmin',
as:'admin'
});
await sequelize.sync({alter:true});
})();
module.exports = Chat;
<!-- end snippet -->
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
const sequelize = require('../config/sequelize');
const {DataTypes} = require('sequelize');
const Chat = require('./Chats');
const User = require('./User')
let Message = sequelize.define('Message',{
content:{
type:DataTypes.TEXT,
allowNull:false
},
},{freezeTableName:true});
(async function(){
Message.belongsTo(User,{
foreignKey:'sender'
})
Message.belongsTo(Chat,{
foreignKey:'chat_id'
})
Chat.belongsTo(Message,{as:'lastMessage',foreignKey:'latest_message',targetKey:'id'})
await sequelize.sync({alter:true});
})();
module.exports = Message;
<!-- end snippet -->
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
const User = require('./models/User');
const Chat = require('./models/Chats');
const Message = require('./models/Messages');
(async function(){
try{
await sequelize.authenticate();
console.log('//// connection successful');
await sequelize.sync({alter:true});
}catch(err){
console.log('!!!! Error in connecting to DB',err);
}
})();
<!-- end snippet -->
答案1
得分: 1
- 不要在每个模型定义后使用 await sequelize.sync()。
只需在主要代码中使用一次。 - 从Chat模型中最后一个定义的关系 Chat.belongsTo(Message,...) 中,删除 targetKey: 'id'。
英文:
So, if anyone is facing the same issue, here's how I fixed it for now:
- Don't use await sequelize.sync() after every model definition.
You should use it once in the main code only. - From that last
relationship defined in Chat model Chat.belongsTo(Message,...),
remove targetKey:'id'.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论