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

TypeORM如何对关联关系做条件查询?查找包含指定用户ID的Friendship记录

查询Friendship表匹配指定用户ID的实现方案

假设你需要匹配的目标用户ID为targetUserId,两种实现方式如下:

1. Repository 实现

直接使用TypeORM Repository提供的find方法,通过嵌套where条件匹配关联属性即可:

import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Friendship } from './entities/friendship.entity';

// 类中注入Repository
constructor(
  @InjectRepository(Friendship)
  private readonly friendshipRepository: Repository<Friendship>,
) {}

// 查询逻辑
async getFriendshipsByUserId(targetUserId: number) {
  return this.friendshipRepository.find({
    where: {
      friends: {
        user: {
          id: targetUserId
        }
      },
      // 可额外加其他过滤条件,比如只查已通过的好友申请
      // accepted: true
    },
    // 如果不需要返回friends关联数据,可关闭eager加载提升性能
    // relations: []
  });
}

2. QueryBuilder 实现

适合需要自定义查询逻辑的场景,手动控制关联和过滤规则:

async getFriendshipsByUserId(targetUserId: number) {
  return this.friendshipRepository
    .createQueryBuilder('friendship')
    // 关联friends中间表,如果不需要返回中间表数据可以换成leftJoin
    .leftJoinAndSelect('friendship.friends', 'userToFriendship')
    // 关联用户表,如果不需要返回用户数据可以换成leftJoin
    .leftJoinAndSelect('userToFriendship.user', 'user')
    .where('user.id = :targetUserId', { targetUserId })
    // 可额外加其他过滤条件
    // .andWhere('friendship.accepted = :accepted', { accepted: true })
    .getMany();
}

两种方式的选择建议

  • 简单查询优先选Repository方式,语法简洁,不易出错
  • 复杂查询、需要做性能优化的场景选QueryBuilder,自由度更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 08:15:04