Sequelize - 无法添加或更新子行:外键约束失败
Posted
技术标签:
【中文标题】Sequelize - 无法添加或更新子行:外键约束失败【英文标题】:Sequelize - Cannot add or update a child row: a foreign key constraint fails 【发布时间】:2016-09-28 17:32:12 【问题描述】:我有一个问题,我无法使用特定的对象值来创建记录。当它执行插入命令时,在命令开始后立即抛出错误,并且永远不会创建记录。错误出现在我的路线中的userId:user.user_id
。
Unhandled rejection SequelizeForeignKeyConstraintError: ER_NO_REFERENCED_ROW_2: Cannot add or update a child row: a foreign key constraint fails (`test_db`.`member`, CONSTRAINT `member_ibfk_2` FOREIGN KEY (`user_id`) REFERENCES `organization` (`organization_id`) ON DELETE CASCADE ON UPDATE CASCADE)
这是模型上的关系:
这是记录的 SQL:
Executing (default): INSERT INTO `user` (`user_id`,`email`,`organization_id`,`authentication_token`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'tester@vdfd.com','1','f800127f4b345d1af54d23f566eca88859898d70','2016-05-30 21:39:19','2016-05-30 21:39:19');
This user:[object SequelizeInstance:user]
41
Executing (default): INSERT INTO `member` (`member_id`,`member_email`,`organization_id`,`user_id`,`updatedAt`,`createdAt`) VALUES (DEFAULT,'tester@vdfd.com','1',41,'2016-05-30 21:39:19','2016-05-30 21:39:19');
路线:
.post(function(req, res, user)
var token;
User.create(
email: req.body.email,
organizationId: req.body.organizationId,
authenticationToken: crypto.randomBytes(20).toString('hex')
).then(function(user)
token = user.authenticationToken;
console.log('This user:' + user);
console.log(user.user_id);
return Member.create(
organizationId: req.body.organizationId,
memberEmail: req.body.email,
userId: user.user_id
);
).then(function(authToken)
console.log(authToken);
console.log("Success");
res.redirect('/app/settings/add-users');
)
);
member.js:
module.exports = function(sequelize, DataTypes)
var Member = sequelize.define('member',
memberId:
type: DataTypes.INTEGER,
field: 'member_id',
autoIncrement: true,
primaryKey: true
,
memberEmail:
type: DataTypes.STRING,
field: 'member_email',
isEmail: true,
unique: true
,
organizationId:
type: DataTypes.INTEGER,
field: 'organization_id',
allowNull: true
,
userId:
type: DataTypes.INTEGER,
field: 'user_id',
allowNull: true
,
freezeTableName: true,
);
return Member;
user.js:
var bcrypt = require('bcrypt-nodejs');
module.exports = function(sequelize, DataTypes)
var User = sequelize.define('user',
user_id:
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
,
firstName:
type: DataTypes.STRING,
field: 'first_name'
,
lastName:
type: DataTypes.STRING,
field: 'last_name'
,
email:
type: DataTypes.STRING,
isEmail: true,
unique: true,
set: function(val)
this.setDataValue('email', val.toLowerCase());
,
password: DataTypes.STRING,
organizationId:
type: DataTypes.INTEGER,
field: 'organization_id',
allowNull: true
,
authenticationToken:
type: DataTypes.STRING,
field: 'authentication_token'
,
resetPasswordToken:
type: DataTypes.STRING,
field: 'reset_password_token'
,
resetPasswordExpires:
type: DataTypes.DATE,
field: 'reset_password_expires'
,
freezeTableName: true,
classMethods:
associate: function(db)
User.belongsToMany(db.Organization, through: 'member', foreignKey: 'organizationId')
,
generateHash: function(password)
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
,
,
instanceMethods:
validPassword: function(password)
return bcrypt.compareSync(password, this.password);
,
,
);
return User;
organization.js:
module.exports = function(sequelize, DataTypes)
var Organization = sequelize.define('organization',
organizationId:
type: DataTypes.INTEGER,
field: 'organization_id',
autoIncrement: true,
primaryKey: true
,
organizationName:
type: DataTypes.STRING,
field: 'organization_name'
,
admin: DataTypes.STRING
,
freezeTableName: true,
classMethods:
associate: function(db)
Organization.belongsToMany(db.User, through: 'member', foreignKey: 'user_id' ),
,
);
return Organization;
【问题讨论】:
我的 SQL 有点生疏了,不过看起来像user_id === organization_id
。是否因为没有具有该 ID 的组织而失败?
@Russbear 这些值应该不同。 user_id.organizationId === organization.organizationId
。您认为这与我的问题有关吗?该字段应该是外键的事实是否是我无法使用值操作列的原因?它应该只来自另一个表?
您的模型的屏幕截图看起来像user_id
和organization_id
链接在两个表之间,而您实际上需要organization_id
在这两个表中。该错误似乎是因为此 FK 关系已关闭。
你在用吗? postgresql
看起来您的模型已关闭。做show tables like member;
你应该可以定位错误
【参考方案1】:
问题是你更新了一个表的关系并且你确实改变了 解决方案:如果您从表中删除记录然后进行更改 会好的,不会有sequelize错误
【讨论】:
以上是关于Sequelize - 无法添加或更新子行:外键约束失败的主要内容,如果未能解决你的问题,请参考以下文章
MySql 重启后:#1452 - 无法添加或更新子行:外键约束失败