TypeORM / Postgres-包括至少满足一个条件的所有关系

问题描述 投票:0回答:1

一般来说,我对SQL / TypeORM刚起步,目前正面临一个问题,我想加载与至少有一个参与者已传递用户ID的比赛相关的比赛参与者。该查询可以被认为是“将我的所有比赛与对手一起载入”。我有三个表:

public.match << OneToMany >> public.match_participant << ManyToOne >> public.user

到目前为止,我已经开始做:

select * from public.match m
left join public.match_participant mp on mp."matchId" = m.id
left join public.user u on u.id = mp."userId"
where u.id = 3

和ORM类型

    repository
      .createQueryBuilder('match')
      .leftJoinAndSelect('match.participants', 'participants')
      .leftJoinAndSelect('participants.user', 'user')
      .where('user.id=:id')
      .setParameter('id', 1)
      .getMany();

当然会加载该特定userId的所有匹配项,参与者和用户,但不包括其他参与者。我相信像“子查询”之类的东西可能有用,但我似乎无法弄清楚。

非常感谢您的帮助!

提前感谢。

postgresql subquery relation typeorm
1个回答
0
投票

我认为您甚至不需要查询构建器。

@Entity()
class Match {
  @OneToMany(...)
  participants: MatchParticipant[];
}

@Entity()
class MatchParticipant {
  @ManyToOne(...)
  match: Match;

  @ManyToOne(...)
  participant: Participant;
}

@Entity()
class User {
  @OneToMany(...)
  matches: MatchParticipant[];
}

// ...

repository.manager.find(MatchParticipant, { where: { match: { participants: { participant: { id } } } } });
© www.soinside.com 2019 - 2024. All rights reserved.