sequelizeforeignkeyconstrainterror

camsedfj  于 2021-06-21  发布在  Mysql
关注(0)|答案(0)|浏览(138)

我在使用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;

}
我上下搜索了这个问题的答案,却什么也找不到!非常感谢你的帮助。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题