谢谢你提前阅读!!
我目前正在开发一个应用程序使用SEQUELIZE和NODEJS。
我所挥动的是两个分开的文件中的Model,它们之间有这样的关联:
文件1:
const Sequelize = require("sequelize");
const db = require("../db");
const Project = db.define("project", {
name: {
type: Sequelize.STRING,
allowNull: false,
unique: true
},
content: {
type: Sequelize.STRING,
allowNull: false,
unique: true
}
});
Project.prototype.associate = (models) => {
Project.hasMany(models.User);
};
module.exports = Project;
文件2:
const Sequelize = require("sequelize");
const db = require("../db");
const User = db.define("user", {
username: {
type: Sequelize.STRING,
unique: true,
allowNull: false
},
password: {
type: Sequelize.STRING,
unique: true,
allowNull: false
},
});
User.prototype.associate = (models) => {
User.belongsTo(models.Project);
};
module.exports = User;
我导入这些文件并创建连接,然后Sync()DB,如下所示:
const domainsPath = path.join(__dirname, '../../domains');
//dataBaseConnection is an instance of Sequelize
fs.readdirSync(domainsPath).forEach(domainFileName => {
const domain = dataBaseConnection.import(path.join(domainsPath, domainFileName));
//just adding the objects to a parent return object(dataBase.domains) to use the models later
dataBase.domains[domain.name] = domain;
});
//Executing the associations. I've already tested it, It loads first the Project and then the User
Object.keys(dataBase.domains).forEach(key => {
if (dataBase.domains[key].prototype.hasOwnProperty('associate')) {
dataBase.domains[key].prototype.associate(dataBase.domains);
}
});
//connection Database Sync
dataBaseConnection.sync({ alter: true}).done((result) => {
console.log(`${logsColors.FgGreen} DataBase Conected!!!`);
});
因此,正如您所看到的...我已经设置了{Alter:true}选项配置,因为我仍处于开发阶段。
因此,我的关系默认有一个onDelete = 'SET NULL',并且当nodemoon重新启动我的服务器时... alter:true
删除源表并在我的projectId字段上设置null。
当然,如果我将onDelete更改为“CASCADE”,它将删除所有相关的注册表...
有什么办法可以避免这种情况吗?
最好的,
1条答案
按热度按时间fkvaft9z1#
这个问题已经很老了,但我还是有义务把答案公布出来,因为我花了很长时间来寻找解决这个问题的最简单的方法...(我现在还不想介绍迁移)
这对我有用!