如何在PostgreSQL+TypeORM中实现ENUM排序及关联表条件设置?
ENUM字段在TypeORM中的排序实现
MySQL 场景
TypeORM没有内置的FIELD函数封装,直接用Raw函数包裹原生SQL片段即可实现自定义排序:
import { Raw } from "typeorm"; const [items, total] = await this.findAndCount({ // 其他查询条件 order: { code: Raw(`FIELD(code, 'USD','CAD','AUD','BBD','EUR', 'GBP')`) } });
PostgreSQL 场景
通过Raw函数包裹CASE语句来实现自定义排序逻辑:
import { Raw } from "typeorm"; const [items, total] = await this.findAndCount({ // 其他查询条件 order: { code: Raw(`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: "ASC" // 按CASE结果排序后,再按name升序排列 } });
关联表查询条件与ORDER CASE失效问题解决
关联表查询条件设置
findAndCount的where对象不支持直接嵌套关联表字段条件,需要用andWhere配合字符串语法+参数绑定实现:
import { In } from "typeorm"; const [items, total] = await this.findAndCount({ where: { enable: true, }, join: { alias: 'posts', innerJoinAndSelect: { category: 'posts.category', }, }, andWhere: "category.post_id IN (:...postIds)", parameters: { postIds: params.postId // 传入数组即可,无需额外用In包裹 } });
ORDER中CASE语句失效解决
直接在order对象中写CASE语句不会被解析,必须用Raw函数包裹原生SQL逻辑:
import { Raw } from "typeorm"; const [items, total] = await this.findAndCount({ // 其他查询配置 order: { customSort: Raw(`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: "ASC" } });
内容的提问来源于stack exchange,提问作者Alpin Cleopatra
相关产品推荐
相关产品推荐

