【发布时间】:2021-05-25 12:59:19
【问题描述】:
我有一张产品表
id | code | description
---------------------------------------
1 | 10 | description for product 10
2 | 2 | description for product 2
3 | 1 | description for product 1
这是续集模型
module.exports = class Product extends Model {
static init(sequelize) {
return super.init({
id: {
type: DataTypes.INTEGER,
allowNull: false,
unique: true,
primaryKey: true
},
code: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
description: {
type: DataTypes.STRING,
allowNull: true,
unique: false
}
},{
sequelize,
modelName: 'Product',
tableName: 'products'
})
}
}
我正在尝试使用代码字母数字顺序检索产品,但我得到的是字典顺序,而不是 1 -> 2 -> 10 我得到的是 1 -> 10 -> 2
function getAll(req, res, next) {
models.Products.findAll({
where: {},
order: [
['code', 'ASC']
]
})
.then(products => {
res.send(products)
})
}
我看到在 postgres 中我可以将字段转换为一个
SELECT code
FROM products
ORDER BY code::bytea;
但我不确定sequelize是否可以这样做
更新
我能够使用所选答案进行修复
function getAll(req, res, next) {
models.Products.findAll({
attributes: [
'id',
'code',
[models.sequelize.literal(`case when code ~ '^[0-9]*$' then code::integer else null end`), 'sort_code'],
'description'
]
where: {},
order: [
[models.sequelize.col('sort_code'), 'ASC'],
['code', 'ASC']
]
})
.then(products => {
res.send(products)
})
}
【问题讨论】:
-
您将
code定义为字符串而不是整数是否有令人信服的理由? -
@MikeSherrill'CatRecall' 感谢您的评论,我没有添加到示例中,但是还有一些其他代码以字母开头,后跟一系列字符
标签: postgresql sorting sequelize.js alphanumeric