Sequelize-如何使用N:M关联创建/更新记录(也可以创建/更新)

时间:2019-03-28 19:52:30

标签: javascript sql node.js sequelize.js

我有这样的Sequelize数据库模型(简化):

// Schedule model
const Schedule = sequelize.define('Schedule', {
    capacity: {
        type: DataTypes.INTEGER,
        allowNull: false
    },
}, {
    hooks: {}
});

// Age category model
const AgeCategory = sequelize.define('AgeCategory', {
    key: {
        type: DataTypes.STRING,
        unique: true,
        allowNull: false
    },
    value: {
        type: DataTypes.STRING,
        allowNull: false
    }
});

// Many-to-many association

Schedule.associate = models => {
    // Schedule have many AgeCategories
    Schedule.belongsToMany(AgeCategory, {
        through: 'schedule_ageCategory',
        foreignKey: 'schedule_id'
    });
};

AgeCategory.associate = models => {
    // Many AgeCategories are in many Schedules
    AgeCategory.belongsToMany(Schedule, {
        through: 'schedule_ageCategory',
        foreignKey: 'ageCategory_id',
        onDelete: 'restrict',
        onUpdate: 'restrict'
    });
};

创建:创建新记录时,我正在这样做:

const data = {
        capacity: 10,
        ageCategories: ["EXTRAOLD","YOUNG"] // 'key' from AgeCategory
    };
const transaction = await sequelize.transaction();
let schedule = await Schedule.create(data, {
    isNewRecord: true,
    transaction
});
// Set AgeCategories
await schedule.setAgeCategories(await AgeCategory.findAll({
    where: {
        key: {in: data.ageCategories}
    },
    transaction
}), {transaction});

await transaction.commit();

还有更好的方法吗?

当我需要更新时间表时(例如,我需要设置不同的年龄类别),我迷路了。我该如何更新n:m关联?可以说我输入的数据格式如下:

const data = {
    capacity: 1,
    ageCategories: ["OLD","YOUNG","DEAD"] // 'key' from AgeCategory
};

在这个特定示例中,这意味着我将删除一个关联,并创建两个新的关联。

0 个答案:

没有答案