Sequelize 允许在外键上将 null 设置为 false

问题描述

这是我的一张表的以下代码

const { Model,DataTypes } = require('sequelize');
const Algorithm = require('./algorithm');
const Exchange = require('./exchange');
const User = require('./user');

//@JA - This model defines the api keys for each user's exchange
//@JA - For security reasons in case the database gets hacked the keys will be stored using encryption.
module.exports = function(sequelize){
    class AlgorithmRule extends Model {}
    AlgorithmModel = Algorithm(sequelize);//@JA - Gets a initialized version of Algorithm class
    ExchangeModel = Exchange(sequelize);//@JA - Gets initialized version of the Exchange class
    usermodel = User(sequelize);//@JA - Gets a initialized version of User class

    var AlgorithmRuleFrame = AlgorithmRule.init({
        algorithm_id: {
            type: DataTypes.INTEGER,allowNull: false,references: { 
                model: AlgorithmModel,key: 'id',}
        },exchange_id: {
            type: DataTypes.STRING,references: { 
                model: ExchangeModel,key: 'name',},user_id: {
            type: DataTypes.INTEGER,references: { 
                model: usermodel,type : { //Partial-Canceled implies that the order was partially filled and then canceled.
            type: DataTypes.ENUM('Percent Of Equity','Cash'),defaultValue: 'Percent Of Equity'
        },type_value: { //@JA - This will be either treated as a percentage or 'cash' value for the type chosen for the algorithm.
            type: DataTypes.DECIMAL(20,18),allowNull: false
        },{
      sequelize,modelName: 'AlgorithmRule',indexes: [{ unique: true,fields: ['algorithm_id','exchange_id','user_id'] }]
    });
    return AlgorithmRuleFrame
};

我正在尝试设置它,以便我可以在 algorithm_id 和 exchange_id 以及 user_id 上允许 null:false。我想要它,所以必须有值才能允许任何记录。

我什至无法通过数据库本身手动获取 allowNull:false 。所以我的第一个问题是,这甚至可能吗?

如果是,我该如何使用 sequelize 来实现?

我可以将典型的 hasOne() 与外键命令一起使用,因为这样我就无法创建外键的复合唯一。我能够做到这一点的唯一方法是我使用 references: json 结构的方式。

对于按照我的方式定义的外键引用,我如何允许 null:false?

要清楚这样的事情是行不通的

Task.belongsTo(User,{ foreignKey: { allowNull: false },onDelete: 'CASCADE' })

这行不通,因为我在 3 个外键之间使用复合唯一键,为此我需要引用它的名称,这是不可能的,除非它在我们输入的这些命令之前在表上定义。希望这是有道理的。

非常感谢任何帮助!

解决方法

显然还行

algorithm_id: {
            type: DataTypes.INTEGER,allowNull: false,references: { 
                model: AlgorithmModel,key: 'id',}
        },

这个代码是正确的。 但是如果您已经创建了数据库并且已经定义了外键,它不会通过alter 命令更改allowNull。您必须完全删除表 然后它将允许 allowNull:false 属性起作用。

这让我循环了很长时间,所以我帮助它为其他人节省了很多挫败感。