Skip to content
Advertisement

returning extra column with formatted date

I have a schema(table) like following in seqluelize:

    const schema = sequelize.define("order_entry_header", {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        date: {
            type: DataTypes.TEXT,
        },
        sub_total: {
            type: DataTypes.DOUBLE,
        },
        ...
    });

My requirement is whenever I call or use or include this schema order_entry_header in any place in my app I want date column in to format in a readable text in a different column called date_format

In simple sql this should be something like below:

SELECT 
    id,
    date,
    DATE_FORMAT(date, "%d/%m/%Y") as date_format
    ...
FROM order_entry_header;

I am joining/fetching this table data in numerous places and every-time I have to add extra column to get the formatted date specifically. I want this to be automated.

. .

With instanceMethod it can be performed. but I have to call the method every-time I get the data which is a little confusing sometimes.

. .

Is there any ways to do so?

Advertisement

Answer

You can try to use Default scope (see Scopes)

const schema = sequelize.define("order_entry_header", {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        date: {
            type: DataTypes.TEXT,
        },
        sub_total: {
            type: DataTypes.DOUBLE,
        },
        ...
    }, {
         defaultScope: {
          attributes: [{ include: [[Sequelize.fn('DATE_FORMAT', Sequelize.col('date')), 'date_format']]}]
      active: true
    }
  }
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement