You need to enable JavaScript to run this app. 如何通过TypeORM查询获取用户关联课程的嵌套结构响应?
优惠活动
大模型
产品
解决方案
定价
更多

如何通过TypeORM查询获取用户关联课程的嵌套结构响应?

如何用TypeORM QueryBuilder实现用户嵌套课程的结构化查询

方法一:利用实体关联自动嵌套(推荐)

如果你的Student和Course实体已经配置了一对多关联,直接通过关联字段查询就能自动得到嵌套结构,无需手动处理重复数据。

配置实体关联

先确保两个实体的关联关系正确设置:

// student.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from 'typeorm';
import { Course } from './course.entity';

@Entity('students')
export class Student {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  // 一对多关联:一个学生对应多门课程
  @OneToMany(() => Course, course => course.user)
  courses: Course[];
}
// course.entity.ts
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn } from 'typeorm';
import { Student } from './student.entity';

@Entity('courses')
export class Course {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

  // 多对一关联:多门课程对应一个学生
  @ManyToOne(() => Student, student => student.courses)
  @JoinColumn({ name: 'userId' }) // 对应courses表的userId外键字段
  user: Student;
}

修改QueryBuilder查询

直接通过实体的关联字段s.courses做左连接查询,TypeORM会自动帮你嵌套courses数组:

return await this.studentsRepository
  .createQueryBuilder('s')
  .leftJoinAndSelect('s.courses', 'c')
  .select([
    's.id',
    's.name',
    'c.id',
    'c.title'
  ])
  .getMany();

返回结果会自动呈现你想要的嵌套结构,每个用户对象下包含对应的courses数组。

方法二:手动处理查询结果(无实体关联时适用)

如果不想配置实体关联,可以先查询出平级的原始数据,再用JavaScript手动分组整理:

获取原始平级数据

用getRawMany()获取未被TypeORM实体映射的原始数据,避免重复实体干扰:

const rawData = await this.studentsRepository
  .createQueryBuilder('s')
  .leftJoin('courses', 'c', 's.id = c.userId')
  .select([
    's.id',
    's.name',
    'c.id AS courseId',
    'c.title'
  ])
  .getRawMany();

手动分组生成嵌套结构

用reduce方法将同一用户的课程合并到courses数组中:

const structuredResult = rawData.reduce((acc, item) => {
  const existingStudent = acc.find(student => student.id === item.s_id);
  
  if (existingStudent) {
    // 仅当课程存在时添加到数组(处理无课程的用户)
    if (item.courseId) {
      existingStudent.courses.push({
        courseId: item.courseId,
        title: item.title
      });
    }
  } else {
    // 创建新用户对象,初始化courses数组
    const newStudent = {
      id: item.s_id,
      name: item.s_name,
      courses: item.courseId ? [{ courseId: item.courseId, title: item.title }] : []
    };
    acc.push(newStudent);
  }
  
  return acc;
}, [] as Array<{ id: number; name: string; courses: Array<{ courseId: number; title: string }> }>);

return structuredResult;

处理后就能得到你期望的嵌套格式响应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 03:40:12