Sequelize为什么会出现UnknownConstraintError并删除表格?

huangapple go评论61阅读模式
英文:

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(&#39;../config/sequelize&#39;);
const {DataTypes} = require(&#39;sequelize&#39;);
const User = require(&#39;./User&#39;);

let Chat = sequelize.define(&#39;Chat&#39;,{
    name:{
        type:DataTypes.STRING,
        allowNull:false
    },
    isGroupChat:{
        type:DataTypes.BOOLEAN,
        defaultValue:false
    },
    
},{freezeTableName:true});


(async function(){
    Chat.belongsToMany(User,{through:&#39;ChatUser&#39;});
    User.belongsToMany(Chat,{through:&#39;ChatUser&#39;});
    Chat.belongsTo(User,{
        foreignKey:&#39;groupAdmin&#39;,
        as:&#39;admin&#39;
    });
   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(&#39;../config/sequelize&#39;);
const {DataTypes} = require(&#39;sequelize&#39;);
const Chat = require(&#39;./Chats&#39;);
const User = require(&#39;./User&#39;)

let Message = sequelize.define(&#39;Message&#39;,{
    content:{
        type:DataTypes.TEXT,
        allowNull:false
    },
},{freezeTableName:true});


(async function(){
    Message.belongsTo(User,{
        foreignKey:&#39;sender&#39;
    })
    Message.belongsTo(Chat,{
        foreignKey:&#39;chat_id&#39;
    })
    Chat.belongsTo(Message,{as:&#39;lastMessage&#39;,foreignKey:&#39;latest_message&#39;,targetKey:&#39;id&#39;})
    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(&#39;./models/User&#39;);
const Chat = require(&#39;./models/Chats&#39;);
const Message = require(&#39;./models/Messages&#39;);

(async function(){
    try{
        await sequelize.authenticate();
        console.log(&#39;//// connection successful&#39;);
        await sequelize.sync({alter:true});
    }catch(err){
        console.log(&#39;!!!! Error in connecting to DB&#39;,err);
    }
})();

<!-- end snippet -->

答案1

得分: 1

  1. 不要在每个模型定义后使用 await sequelize.sync()
    只需在主要代码中使用一次。
  2. 从Chat模型中最后一个定义的关系 Chat.belongsTo(Message,...) 中,删除 targetKey: 'id'。
英文:

So, if anyone is facing the same issue, here's how I fixed it for now:

  1. Don't use await sequelize.sync() after every model definition.
    You should use it once in the main code only.
  2. From that last
    relationship defined in Chat model Chat.belongsTo(Message,...),
    remove targetKey:'id'.

huangapple
  • 本文由 发表于 2023年4月11日 07:06:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75981341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定