使用Sequelize和Node.js,我在单独的文件中有两个模型,它们之间存在关联:
文件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()
数据库:
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
字段上设置为空。如果我尝试onDelete
到CASCADE
,它会删除所有相关的注册表。如何避免这种情况?
1条答案
按热度按时间ki1q1bka1#
这对我很管用。