Sequelize - 无法添加或更新子行:外键约束失败

问题描述 投票:0回答:1

我遇到一个问题,无法使用特定的对象值来创建记录。当它执行插入命令时,命令开始后会立即抛出错误,并且永远不会创建记录。错误出现在我的路线中的

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,'[email protected]','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,'[email protected]','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;
}

用户.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;
}

组织.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;
}
mysql node.js sequelize.js
1个回答
0
投票

问题是你更新了表的关系并且你确实改变了 解决方案:如果您从表中删除记录然后进行更改 就OK了,不会出现sequelize错误

© www.soinside.com 2019 - 2024. All rights reserved.