sqlite 如何同步({ALTER:TRUE})保持关联表数据一致?

6jjcrrmo  于 2022-11-14  发布在  SQLite
关注(0)|答案(1)|浏览(196)

使用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字段上设置为空。如果我尝试onDeleteCASCADE,它会删除所有相关的注册表。如何避免这种情况?

ki1q1bka

ki1q1bka1#

await sequelize.sync({ alter: { drop: false } });

这对我很管用。

相关问题