关于Enum字段排序,如果使用MySQL,这种方式可以按Enum字段的顺序排序:
ORDER BY FIELD(code, 'USD','CAD','AUD','BBD','EUR', 'GBP')
对于PostgreSQL来说,可能没有内置的方法,但这种方法有效:
SELECT * FROM currency_codes
ORDER BY
CASE
WHEN code='USD' THEN 1
WHEN code='CAD' THEN 2
WHEN code='AUD' THEN 3
WHEN code='BBD' THEN 4
WHEN code='EUR' THEN 5
WHEN code='GBP' THEN 6
ELSE 7
END,name;
如何使用TypeORM?我在那里没有找到field
函数。
关于设置关系表条件的查找方法,我在下面尝试了这种方法(andWhere
块(
const [items, total] = await this.findAndCount({
where: {
enable: true,
},
join: {
alias: 'posts',
innerJoinAndSelect: {
category: 'posts.category',
},
},
//andWhere: {
// 'category.post_id': In(params.postId), // It doesn't work
//},
order: { CASE WHEN code='USD' THEN 1 ... }, // It doesn't work
});
在Postgres中,您可以创建一个类型枚举,然后定义该类型的列并对该列进行排序。
枚举类型中值的顺序是值是在创建类型时列出的。所有标准比较枚举支持运算符和相关聚合函数。
所以你可以:
create type currency_type as enum ( 'USD','CAD','AUD','BBD','EUR', 'GBP');
create table payments( id integer generated always as identity
primary key
, cust_id integer
, currency_code currency_type
) ;
select *
from payments
order by currency_code;
此外,如果更改枚举以添加新值,则排序会自动调整为添加值。(见演示(
很抱歉,我不知道TypeORM,所以不能提供,但在创建枚举后使用它应该不困难,可能会创建它。