在TypeORM的where选项中为同一行两列设置条件的方法
TypeORM实现双列优先级条件判断
你需要的是优先级条件判断:优先用postpondedDate(非空时)判断是否大于当前时间,为空时则用createdAt判断。TypeORM支持通过两种方式实现这个逻辑:
方法1:使用Raw函数编写原生SQL片段
直接在where选项中用Raw拼接SQL逻辑,适合简单场景:
async handleCron(){ const now = new Date(); const activeStudents = await this.invoiceService.find({ select: ['id', 'student', 'postpondedDate', 'createdAt'], relations: ['student'], where: Raw(alias => ` (${alias}.postpondedDate IS NOT NULL AND ${alias}.postpondedDate > :now) OR (${alias}.postpondedDate IS NULL AND ${alias}.createdAt > :now) `, { now }) }); }
alias会自动替换为当前表的别名(TypeORM内部处理)- 通过
:now绑定参数,避免SQL注入 - 逻辑完全对应你的需求:非空时校验
postpondedDate,为空时校验createdAt
方法2:使用QueryBuilder(推荐,类型安全)
对于复杂查询,QueryBuilder更直观且类型友好,跨数据库兼容性更好:
async handleCron(){ const now = new Date(); const activeStudents = await this.invoiceService .createQueryBuilder('invoice') .select(['invoice.id', 'invoice.postpondedDate', 'invoice.createdAt']) .leftJoinAndSelect('invoice.student', 'student') .where('invoice.postpondedDate IS NOT NULL AND invoice.postpondedDate > :now', { now }) .orWhere('invoice.postpondedDate IS NULL AND invoice.createdAt > :now', { now }) .getMany(); }
- 用
leftJoinAndSelect替代relations,更灵活控制关联查询 - 通过
where+orWhere拼接逻辑,可读性更强 - 同样通过参数绑定避免SQL注入
注意事项
- 确保数据库中
postpondedDate字段允许为NULL(实体定义中要设为nullable: true) MoreThan(new Date())本质就是SQL中的> 当前时间,两种方法都等价于你注释里的需求
内容的提问来源于stack exchange,提问作者Omar Zaoujal
相关产品推荐
相关产品推荐

