首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从orm查询中获取准备好的响应

从orm查询中获取准备好的响应
EN

Stack Overflow用户
提问于 2022-11-01 18:54:38
回答 1查看 29关注 0票数 1

在需要分配给用户的所有课程时,我有一个简单的查询:

我有两张桌子,即students & courses

代码语言:javascript
运行
复制
return await this.studentsRepository
      .createQueryBuilder('s')
      .leftJoinAndSelect('courses', 'c', 's.id = c.userId')
      .select([
        's.id',
        's.name',
        'c.id AS courseId',
        'c.title'
      ])
      .getMany();
}

因此,目前我从上面的查询中得到了这样的响应:

代码语言:javascript
运行
复制
id  name  courseId  title   
1   user 1  11  course 1
1   user 1  22  course 2
2   user 2  33  course 3
3   user 3  44  course 4

但实际上我想要这样的回应:

代码语言:javascript
运行
复制
[
  {
    "id": 1,
    "name": "user 1",
    "courses": [
      {
        "courseId": 11,
        "title": "course 1",
      },
      {
        "courseId": 22,
        "title": "course 2",
      }
    ]
  },
  {
    "id": 2,
    "name": "user 2",
    "courses": [
      {
        "courseId": 33,
        "title": "course 3",
      }
    ]
  },
  {
    "id": 3,
    "name": "user 3",
    "courses": [
      {
        "courseId": 44,
        "title": "course 4",
      }
    ]
  }
]

所以,我怎样才能作出这样的回应呢?

EN

回答 1

Stack Overflow用户

发布于 2022-11-03 15:40:07

我认为,如果正确定义了该列,应该只需删除select即可。

代码语言:javascript
运行
复制
# students table
@ManyToMany(type => Courses)
@JoinTable()
courses!: Promise<Courses[]>;
代码语言:javascript
运行
复制
return await this.studentsRepository
      .createQueryBuilder('students')
      .leftJoinAndSelect('students.courses', 'courses')
      .getMany();
}

https://orkhan.gitbook.io/typeorm/docs/many-to-many-relations#loading-many-to-many-relations

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74280560

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档