如何在n:m关联中进行单向限制?

时间:2019-04-02 18:10:44

标签: javascript node.js sequelize.js

我在UserTrainerProp(用户属性)之间有N:M关联。这是简化的示例:

/**
 * User
 */
const User = sequelize.define('User', {
    // USER ATTRIBUTES... NOT IMPORTANT
});

User.associate = models => {
    // User have many TrainerProps
    User.belongsToMany(TrainerProp, {
        through: 'user_trainerProp',
        foreignKey: 'user_id'
    });
};

/**
 * TrainerProp
 */
const TrainerProp = sequelize.define('TrainerProp', {
    // TRAINER PROP ATTRIBUTES... NOT IMPORTANT
});

TrainerProp.associate = models => {
    // TrainerProp belongs to many Users
    TrainerProp.belongsToMany(User, {
        through: 'user_trainerProp',
        foreignKey: 'trainerProp_id',
        onDelete: 'restrict',
        onUpdate: 'restrict'
    });
};

/**
 * user_trainerProp table (n:m)
 */
const user_trainerProp = sequelize.define('user_trainerProp', {
    trainerProp_id: DataTypes.INTEGER,
    user_id: DataTypes.INTEGER,
}, {
    timestamps: false,
    freezeTableName: true
});

如您所见,我对Trainer进行了onUpdate和onDelete限制,因此当我尝试删除TrainerPropuser_trainerProp中使用的内容时,它将抛出ForeignKeyConstraintError

我的问题是,当我尝试删除UserTrainerProps的内容时,我也受到限制。我希望,当我删除User时,user_trainerProp中的所有行也将被删除,并且不会出现错误...

如何实现?

0 个答案:

没有答案