SequelizeForeignKeyConstraintError

时间:2018-07-11 02:03:39

标签: mysql sql foreign-keys sequelize.js

我在使用Sequelize进行关联时遇到问题。我正在尝试创建一个任务,它应该属于用户和部门。

这是我的任务文件:

module.exports = function (sequelize, DataTypes) {
var Task = sequelize.define("Task", {
    id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    task_name: {
        type: DataTypes.STRING,
        notNull: true
    },

    description: {
        type: DataTypes.STRING,
        notNull: true
    },

    completed: {
        type: DataTypes.BOOLEAN
    }
}, {
    tableName: 'tasks',
    timestamps: false,
});

Task.associate = function (models) {
    Task.belongsTo(models.Department, {
        onDelete: 'CASCADE',
        allowNull: true
    });

    Task.belongsTo(models.User, {
        onDelete: 'CASCADE',
        allowNull: true
    });
}



return Task;

};

我的部门文件:

module.exports = function (sequelize, DataTypes) {
var Department = sequelize.define("Department", {
    id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    departmentName: DataTypes.STRING,
    description: {
        type: DataTypes.STRING,
        notNull: true
    }
}, {
    tableName: 'departments',
    timestamps: false,
});

Department.associate = function (models) {
    Department.belongsTo(models.Project, {
        allowNull: true
    });

    Department.hasMany(models.Task, {
        allowNull: true
    });

}

return Department;

};

最后是我的用户文件:

const bcrypt = require('bcryptjs');

module.exports = function (sequelize, Sequelize) {

var User = sequelize.define('User', {
    id: {
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
    },
    fullname: {
        type: Sequelize.STRING,
        notEmpty: true
    },
    username: {
        type: Sequelize.TEXT
    },
    email: {
        type: Sequelize.STRING,
        validate: {
            isEmail: true
        }
    },
    password: {
        type: Sequelize.STRING,
        allowNull: false
    },
    last_login: {
        type: Sequelize.STRING
    }

}, {
    tableName: 'users',
    timestamps: false
});

User.associate = function (models) {
    User.hasMany(models.Task, {});
}

User.prototype.validPassword = function (password) {
    return bcrypt.compareSync(password, this.password);
};

User.hook("beforeCreate", (instance) => {
    if (instance.password) {
        instance.password = bcrypt.hashSync(instance.password, bcrypt.genSaltSync(10), null);
    }
});
return User;

}

我已经在谷歌上搜索了这个问题的答案,但找不到任何东西!非常感谢您的帮助。

0 个答案:

没有答案