繁体   English   中英

Typeorm Postgres 选择双嵌套关系等于值的位置

[英]Typeorm Postgres select where double nested relation is equal to value

我有如下关系:

匹配
ID
团队
@OneToMany(() => Team, (team) => team.match)
  teams: Team[];
团队
ID
球员
 @OneToMany(() => Player, (player) => player.team)
  players: Player[];

@ManyToOne(() => Match)
  match: Match;
球员
ID
名称
@ManyToOne(() => Player, { nullable: true })
  player: Player;

  @ManyToOne(() => Team)
  team: Team;

从这里我想选择玩家名称为“x”的比赛。

目前我有以下几点:

const matchDataQuery = getRepository(Match)
              .createQueryBuilder('match')
              .select('match.id')
              .leftJoinAndSelect('match.teams', 'teams')
              .leftJoinAndSelect('teams.players', 'players')
              .where('players.name = :name', { name: player.name })

但这只会返回与我的位置匹配的单个团队和单个玩家。

{
  id: 1,
  teams: [
    {
      id: 'team1',
      players: [
        {
          id: 'player1',
           name: 'x'
        }
      ]
    }
  ]
}

这个id: 1比赛实际上有超过 1 个团队,每个团队有超过 1 个玩家,但它只返回每个的单个实体。

我需要它来返回比赛中所有有该球员参加的球队和所有球员。 我怎样才能做到这一点?

谢谢!

在关系中:

@ManyToOne(() => Match)
  match: Match;

也许应该是@ManyToMany,而不是@ManyToOne。

因为一支team要打很多matches

我能够通过使用子查询来解决我的问题

const matchDataQuery = getRepository(Match)
              .createQueryBuilder('match')
              .leftJoinAndSelect('match.teams', 'teams')
              .leftJoinAndSelect('teams.players', 'players')
              .where((qb) => {
                const subQuery = qb
                  .subQuery()
                  .select('match.id')
                  .from(Match, 'match')
                  .leftJoin('match.teams', 'teams')
                  .leftJoin('teams.players', 'players')
                  .where('players.name = :name')
                  .getQuery();
                return 'match.id IN ' + subQuery;
              })
              .setParameter('name', 'WhateverName')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM