简体   繁体   中英

Sequelize order by column name

I am trying to order by column name in Sequelize

Here is my model

var Milestones = sequelize.define('milestones', {
  milestoneId: Sequelize.INTEGER,
  data: Sequelize.JSON,
  repository: Sequelize.STRING
});

Database is PostegreSql 9.5

var dialect = 'postgres',
    protocol = 'postgres';

var sequelize = new Sequelize(dbConfig.database, dbConfig.user, dbConfig.password, {
  host: dbConfig.host,
  dialect: dialect,
  protocol: protocol,
  dialectOptions: {
    timeout: 30
  },
  pool: {
    max: 5,
    min: 0,
    idle: 30000,
    maxConnections: 5,
    maxIdleTime: 30
  },
  logging: false
});

Here is my query

models.Milestones.findAll({
      where: {
        repository: req.body.repository
      },
      order: 'milestoneId'
    }).then(function (values) {
      // do something
    });

Here is my error

Unhandled rejection SequelizeDatabaseError: column "milestoneid" does not exist

So problem is that I wanna order by milestoneId but Sequelize is actually trying to order by milestoneid (notice the lack of camel case).

If I change to order by repository everything works, so the issue at this point seems to be related to the conversion to lowercase by Sequelize.

Any suggestions other than to rename the column in database to lowercase?

Thank you

Update your model with a field and it will be fine

var Milestones = sequelize.define('milestones', {
  milestoneId: {
    type: Sequelize.INTEGER,
    field: 'milestoneId'
  },
  data: Sequelize.JSON,
  repository: Sequelize.STRING
});

EDIT:

also update the ordering with

order: ['milestoneId']

I had a similar issue with PostGreSQL and Oracle (with Sequelize-Oracle). Sequelize automatically adds quotes for many parameters.

Do you have "quoteIdentifiers" option turned off ? (default is on).

Maybe the problem isn't :
- order by milestoneid or order by milestoneId
But instead it can be :
- order by 'milestoneid' (with quotes causing the issue).

The doc says :

[options.quoteIdentifiers=true] : Boolean, Set to false to make table names and attributes case-insensitive on Postgres and skip double quoting of them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM