Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize - map fields to field alias in model definition

I am defining a Sequelize model to map fields from existing tables in my database. However, the field names in the table are long and not developer-friendly.

Is it possible to map the database field names to aliases in the model definition so that my service has more developer-friendly model property names to work with?

Example:

This...

// Horrible field names
module.exports = (sequelize, DataTypes) =>
  sequelize.define('Transaction', {
    f_curr_finaccount__amount: DataTypes.DECIMAL,
    f_curr_finaccount__tx_type: DataTypes.STRING,
    f_finaccount__currency_iso_id: DataTypes.STRING,
    f_lex_finaccount__tx_atomic_status: DataTypes.STRING
  }, {
    schema: 'fins',
    tableName: 'fins_financialaccounttransaction',
    timestamps: false
  })

...becomes...

// Developer-friendly field names
module.exports = (sequelize, DataTypes) =>
  sequelize.define('Transaction', {
    amount: {
      type: DataTypes.DECIMAL,
      fieldName: 'f_curr_finaccount__amount'
    },
    type: {
      type: DataTypes.STRING,
      fieldName: 'f_curr_finaccount__tx_type'
    },
    currency: {
      type: DataTypes.STRING,
      fieldName: 'f_finaccount__currency_iso_id'
    },
    status: {
      type: DataTypes.STRING,
      fieldName: 'f_lex_finaccount__tx_atomic_status'
    }
  }, {
    schema: 'fins',
    tableName: 'fins_financialaccounttransaction',
    timestamps: false
  })
like image 914
travega Avatar asked Nov 01 '25 01:11

travega


1 Answers

Exactly as you did but the name of the attribute is just field. It will be the same for all columns including foreign keys.

// Developer-friendly field names
module.exports = (sequelize, DataTypes) =>
  sequelize.define('Transaction', {
    amount: {
      type: DataTypes.DECIMAL,
      field: 'f_curr_finaccount__amount'
    },
    type: {
      type: DataTypes.STRING,
      field: 'f_curr_finaccount__tx_type'
    },
    currency: {
      type: DataTypes.STRING,
      field: 'f_finaccount__currency_iso_id'
    },
    status: {
      type: DataTypes.STRING,
      field: 'f_lex_finaccount__tx_atomic_status'
    }
  }, {
    schema: 'fins',
    tableName: 'fins_financialaccounttransaction',
    timestamps: false
  })
like image 200
Ellebkey Avatar answered Nov 03 '25 13:11

Ellebkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!