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

TypeORM使用Repository查询OneToMany关联实体并按需预加载数据

TypeORM 单次查询预加载OneToMany关联并筛选子实体方案

你原有写法的问题是把子表User的name字段写在了主表Role的根where条件中,TypeORM会将其识别为Role表的字段,导致查询结果不符合预期。以下是两种可行的实现方案:

方案1:使用find方法(适用于TypeORM 0.3+版本)

直接在where配置中指定关联实体的筛选条件,写法更简洁:

import { ILike } from 'typeorm';

const rolesRepository = getRepository(Role);
const roles = await rolesRepository.find({
  relations: ['users'],
  where: {
    users: {
      name: ILike('%john%')
    }
  }
});

方案2:使用QueryBuilder(全版本兼容,灵活性更高)

通过自定义关联查询条件实现,可控性更强:

import { ILike } from 'typeorm';

const rolesRepository = getRepository(Role);
const roles = await rolesRepository
  .createQueryBuilder('role')
  // 关联用户表,同时添加用户姓名筛选条件,仅预加载符合要求的用户
  .leftJoinAndSelect('role.users', 'user', 'user.name ILIKE :userName', { userName: '%john%' })
  // 过滤掉没有匹配用户的角色,避免返回users为空的角色数据
  .where('user.id IS NOT NULL')
  .getMany();

以上两种方案都不需要在实体配置中添加eager: true,仅在本次查询中生效,不会造成全局过度拉取的问题,返回结果和你预期的结构完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 12:15:00