1

I have a model (Article) with a field (the name is type) of type ENUM('source', 'translated') and would like to return 1 article ordered by the type field. Source articles should be returned before translated articles. Something like:

Article.findOne(order: [
    {
        type: [
            'source',
            'translated'
        ]
    }
]);

Unfortunately there appears to be no built-in solution for sorting by enums. Instead I probably have to sort by case, but I couldn't find any documentation on how to do this with Sequelize.

What would be the conventional approach here?

Community
  • 1
  • 1
Tom
  • 8,536
  • 31
  • 133
  • 232

2 Answers2

3

Sorting by CASE is hard to do in sequelize, but sort by field (the second answer in your linked post) should be possible:

order: sequelize.fn('field', sequelize.col('type'), 'source', 'translated')

It's only supported by mysql as far as I know though

Jan Aagaard Meier
  • 28,078
  • 8
  • 95
  • 66
0

For sorting by CASE you should use sequelize.literal

order: sequelize.literal(`case when type='source then '0' when type='tranlated' then '1' else type end`)