You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用TypeORM QueryBuilder实现多Where条件的查询逻辑

TypeORM QueryBuilder 实现对应SQL查询的方案

以下是你给出的原始SQL逻辑(补充了省略的SELECT部分):

SELECT * FROM customers
WHERE favorite_website = 'techonthenet.com'
AND customer_id > 6000;

你可以通过两种常用的QueryBuilder调用方式实现相同逻辑,前提是你已经提前定义了对应customers表的TypeORM实体类Customer:

方式1:从Repository实例创建QueryBuilder

import { getRepository } from 'typeorm';
// 替换为你自己的Customer实体存放路径
import { Customer } from './entities/Customer';

const result = await getRepository(Customer)
  // 给查询的customer表设置别名,后续条件里都用这个别名前缀
  .createQueryBuilder('customer')
  // 第一个查询条件用where,参数用占位符写法避免SQL注入
  .where('customer.favorite_website = :website', { website: 'techonthenet.com' })
  // 额外的AND条件用andWhere
  .andWhere('customer.customer_id > :minCustomerId', { minCustomerId: 6000 })
  // 查询多条匹配的实体对象,查单条用getOne,查原始数据用getRawMany
  .getMany();

方式2:从Connection实例创建QueryBuilder

import { getConnection } from 'typeorm';
import { Customer } from './entities/Customer';

const result = await getConnection()
  .createQueryBuilder()
  .select('customer')
  .from(Customer, 'customer')
  .where('customer.favorite_website = :website', { website: 'techonthenet.com' })
  .andWhere('customer.customer_id > :minCustomerId', { minCustomerId: 6000 })
  .getMany();

注意事项

  • 所有查询值都推荐通过参数占位符传递,不要直接拼接字符串到查询语句中,避免SQL注入风险
  • 如果不需要返回完整实体,只需要指定字段,可以修改select方法参数,比如.select(['customer.customer_id', 'customer.email'])
  • 要是只需要原始数组结构的返回结果,把结尾的getMany()替换为getRawMany()即可

内容的提问来源于stack exchange,提问作者Kusal Lamsal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 16:06:05