sequelize外键关联报错SequelizeDatabaseError: Cant write; duplicate key in table #sql-454_d
Assistance.belongTo(User)会报以下错误:
ALTER TABLE `assistance` ADD CONSTRAINT `assistance_user_id_foreign_idx` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE;
Unhandled rejection SequelizeDatabaseError: Can't write; duplicate key in table '#sql-454_d'
at Query.formatError (/home/hale/workspace/issue-tracking-system/node_modules/sequelize/lib/dialects/mysql/query.js:223:16)
at Query.connection.query [as onResult] (/home/hale/workspace/issue-tracking-system/node_modules/sequelize/lib/dialects/mysql/query.js:55:23)
at Query.Command.execute (/home/hale/workspace/issue-tracking-system/node_modules/mysql2/lib/commands/command.js:30:12)
at Connection.handlePacket (/home/hale/workspace/issue-tracking-system/node_modules/mysql2/lib/connection.js:515:28)
at PacketParser.onPacket (/home/hale/workspace/issue-tracking-system/node_modules/mysql2/lib/connection.js:94:16)
at PacketParser.executeStart (/home/hale/workspace/issue-tracking-system/node_modules/mysql2/lib/packet_parser.js:77:14)
at Socket.<anonymous> (/home/hale/workspace/issue-tracking-system/node_modules/mysql2/lib/connection.js:102:29)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at addChunk (_stream_readable.js:264:12)
at readableAddChunk (_stream_readable.js:251:11)
at Socket.Readable.push (_stream_readable.js:209:10)
at TCP.onread (net.js:587:20)
原因是会在Assistance表中自动添加外键约束,如果不需要外键约束则可以这样设置: Assistance.belongsTo(User, { constraints: false });