0

Using Sequelize 6, I have a model, associated with tables, that has capital letters in some columns and snake case in others (the columns are not created_at or updated_at).

The underscored model configuration seems to affect each attribute associated with the corresponding table columns. Is there a way to override the model level underscored configuration such that the the attribute associated with the table column retains the original column name of the table?

Code example:

  const someModel = sequelize.define('some_table', {
    'id': {
      type: dataTypes.BIGINT,
      primaryKey: true,
      autoIncrement: true,
    },
    'other_table_id': {
      type: dataTypes.BIGINT,
      allowNull: false,
      references: {
        model: 'other_table',
        key: 'id',
        deferrable: INITIALLY_IMMEDIATE,
      },
    },
    'CAPITAL_letterColumn': {
      type: dataTypes.STRING,
      allowNull: true,
      defaultValue: null,,
    }
  }, {
      timestamps: false,
      paranoid: false,
      // underscored: true, // true === snake case, false === camelcase
    }
  });

  someModel.associate = (models) => {
    someModel.belongsTo(models.other_table, { foreignKey: 'other_table_id', targetKey: 'id' });
  };

I get the following error:

UnhandledPromiseRejectionWarning: SequelizeDatabaseError: column "otherTableId" does not exist

If I set

underscored: true

I get the following error:

UnhandledPromiseRejectionWarning: SequelizeDatabaseError: column "c_a_p_i_t_a_l_letter_column" of relation "some_table" does not exist
4

1 回答 1

0

看起来在模型定义中添加字段属性可以解决问题。

'other_table_id': {
  field: 'other_table_id', // <-- this line 
  type: dataTypes.BIGINT,
  allowNull: false,
  references: {
    model: 'other_table',
    key: 'id',
    deferrable: INITIALLY_IMMEDIATE,
  },
},
于 2020-12-22T05:21:05.370 回答