【问题标题】:Sequelize belongsToMany self reference not creating foreign keySequelize belongsToMany 自引用不创建外键
【发布时间】:2017-01-16 12:21:55
【问题描述】:

我正在使用 sequelize 创建一个自引用的 belongsToMany 关系,并将模型作为 through 参数。

但是,当它创建表时,它只会为其中一个关系创建一个外键。

型号:

const client = sequelize.define('client', {
    ClientId: {
        type: DataTypes.UUID,
        primaryKey: true,
        allowNull: false,
        defaultValue: DataTypes.UUIDV4()
    },
    AccessMode: {
        type: DataTypes.ENUM('allow_all', 'deny_all', 'selective'),
        allowNull: false
    }
}, {
    classMethods: {
        associate: function (models) {
            // Tons of other relationships here

            client.belongsToMany(models.client, {
                through: models.clientAccess,
                as: 'clientsWithAccess',
                foreignKey: 'ClientId'
            });

            client.belongsToMany(models.client, {
                through: models.clientAccess,
                as: 'accessToClients',
                foreignKey: 'AccessingClientId'
            });

        }
    }

});

直通模型:

const clientAccess = sequelize.define('clientAccess', {
    Access: {
        type: DataTypes.ENUM('allow', 'deny'),
        allowNull: false
    }
}, {
    timestamps: false
});

生成的表只有 AccessMode 和 AccessingClientId 列。并且由于某种原因,AccessingClientId 被设置为主键。

如果我切换 belongsToMany() 语句的位置,那么表中字段的名称也会颠倒。

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    这是使用 belongsToMany() 方法的 otherKey 属性解决的。

            client.belongsToMany(models.client, {
                through: models.clientAccess,
                as: 'clientsWithAccess',
                foreignKey: 'ClientId',
                otherKey: 'AccessingClientId'
            });
    
            client.belongsToMany(models.client, {
                through: models.clientAccess,
                as: 'accessToClients',
                foreignKey: 'AccessingClientId',
                otherKey: 'ClientId'
            });
    

    这样,表就在数据库中正确创建了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-05
      • 2018-11-12
      • 1970-01-01
      • 2021-12-21
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      相关资源
      最近更新 更多