如何使用TypeORM对ENUM字段顺序进行排序并为PostgreSQL设置关系表条件?

问题描述 投票:0回答:2

关于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
});
postgresql enums typeorm
2个回答
2
投票

在 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,所以无法提供,但在创建枚举后使用它应该不难,创建它是可能的。


0
投票

nestjs 枚举实体的顺序与您在代码中定义的顺序相同。 例如:

export enum ResumeStatus {
  Done = 'done',
  Init = 'init',
  Doing = 'doing',
  Error = 'error',
}

ASC 顺序:完成、初始化、执行、错误

© www.soinside.com 2019 - 2024. All rights reserved.