SequelizeJS中的自定义Postgresql序列Nextval

时间:2017-02-28 06:42:35

标签: postgresql sequelize.js

如何在sequelizeJS模型中定义序列nextval()

sequelizeJS中是否有nextval()可用的预定义函数,

在sequelize define模型中编写序列nextval()自定义函数是否有可能?

4 个答案:

答案 0 :(得分:2)

目前没有办法在续集中这样做,请参考

https://github.com/sequelize/sequelize/issues/3555

答案 1 :(得分:1)

如果此时有人也想这样做,我想最好的方法是使用 Sequelize.literal

// on your model

const model = sequelize.define("model", {
  ...attributes,
  customSequence: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: sequelize.Sequelize.literal("nextval('custom_sequence')")
  },
})

// after create a migration for your new column

module.exports = {
  up: async (queryInterface, sequelize) => {
    await queryInterface.sequelize.query("CREATE SEQUENCE custom_sequence start 1020 increment 20",)

    await queryInterface.addColumn('table', 'customSequence', {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: sequelize.Sequelize.literal("nextval('custom_sequence')")
    })
  },

  down: async (queryInterface, sequelize) => {
    await queryInterface.sequelize.query('DROP SEQUENCE custom_sequence')
    await queryInterface.removeColumn('table', 'customSequence')
  }
};

答案 2 :(得分:0)

没有预定义的功能。但是您可以利用原始查询并获得nextval之类的

sequelize.query("SELECT nextval('sequence')", { 
 type: collection.Sequelize.QueryTypes.SELECT 
});

答案 3 :(得分:0)

我能够执行与@sebin发布的类似的操作,并将诺言链接到我的model.create()上,如下所示:

  this.sequelize
    .query("SELECT max(cust_no) + 1 as 'custNo' from employees.customers", {
      type: this.sequelize.Sequelize.QueryTypes.SELECT
    })
    .then(results => {
      return results[0];
    })
    .then(nextPk => {
      const values = Object.assign({}, newCustomer, nextPk);
      return customersModel.create(values);
    })
    .then(newRecord => {
      console.log('newRecord:', newRecord);
    });

在上述情况下,我使用max +1,但该解决方案同样适用于您的序列。