【问题标题】:TypeORM / Postgres - Include all in relation where at least one meets requirementTypeORM / Postgres - 包括至少一个满足要求的所有关系
【发布时间】:2020-05-05 20:52:01
【问题描述】:

总的来说,我对 SQL/TypeORM 非常陌生,我目前面临一个问题,我想加载与至少一个参与者具有传递的用户 ID 的匹配相关的匹配参与者。该查询可以被认为是“加载我与对手的所有比赛”。我有三张桌子:

public.match > public.match_participant > 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 的所有匹配项、参与者和用户,但不包括其他参与者。我相信像“子查询”这样的东西可能有用,但我似乎无法弄清楚。

非常感谢任何帮助!

提前致谢。

【问题讨论】:

  • select * from match match join (select p."matchId" from public.match_participant p where p."userId" = 1) selfMatch on (selfMatch."matchId" = match.id) join match_participant mp on (mp."matchId" = match.id) left join public.user u on mp."userId" = u.id 这似乎是我需要的,但我不知道如何将其转换为 typeORM

标签: postgresql subquery relation typeorm


【解决方案1】:

我认为您甚至不需要查询生成器。

@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 } } } } });

【讨论】:

  • 好吧,我还需要加载关联的用户。所以匹配 + 满足要求的参与者 + 与每个参与者关联的用户
【解决方案2】:

经过大量的反复试验,我学会了如何将纯查询转换为构建器。解决方案如下:

matchRepository
      .createQueryBuilder('match')
      .innerJoin(
        query => {
          return query
            .from(MatchParticipant, 'p')
            .select('p."matchId"')
            .where('p."userId" = :id');
        },
        'selfMatch',
        '"selfMatch"."matchId" = match.id',
      )
      .leftJoinAndSelect('match.participants', 'participants')
      .leftJoinAndSelect('participants.user', 'user')
      .setParameter('id', id)
      .getMany();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多