首页 > 解决方案 > TypeORM - 3 个相关表之间的 LEFT JOIN/INNER JOIN 问题

问题描述

所以我有我无法处理的问题,也许你可以帮助我。所以:我有三个实体——用户、团队、用户团队,其中包含(userId、teamId、teamRole)。UserTeam 是包含复合主键的实体。就像下面的代码:

@Index(["teamId", "userId"], { unique: true })
export class UserTeam {

    @PrimaryColumn("int")
    userId = undefined;

    @PrimaryColumn("int")
    teamId = undefined;

    @ManyToOne(type => Team)
    team = undefined;

    @ManyToOne(type => User)
    user = undefined;

    @Column({
        type: 'enum',
        enum: ['CAPITAN', 'PLAYER'],

    })
    teamRole = "";
}
export class Team {

    @PrimaryGeneratedColumn()
    id = undefined; 
@OneToMany(type => UserTeam, userTeam => userTeam.user)
    userTeams = undefined;
export class User {

    @PrimaryGeneratedColumn()
    id = undefined;

    @OneToMany(type => UserTeam, userTeam => userTeam.team)
    teams = undefined;
} 

所以->我想创建一个查询,它将返回特定团队的所有玩家(用户)。所以我创建了一个查询,例如 eq ({team_id: 1, player: {userId:1, userId:21,userId:34} (而不是 ids,我想要对象只是示例。

getRepository(Team).createQueryBuilder("team")
            .leftJoin("team.users", "userTeam")
            .leftJoin("userTeam.user", "user")
            .getMany()

这返回给我QUERY:

SELECT "team"."id" AS "team_id", "team"."name" AS "team_name", "team"."shortcut" AS "team_shortcut", "team"."nationality" AS "team_nationality", "team"."description" AS "team_description", "team"."imagePath" AS "team_imagePath", "team"."division" AS "team_division" FROM "team" "team" LEFT JOIN "user_team" "userTeam" ON "userTeam"."userId"="team"."id"  LEFT JOIN "user" "user" ON "user"."id"="userTeam"."userId"

问题就在那里,因为我有

 LEFT JOIN "user_team" "userTeam" ON "userTeam"."userId"="team"."id"```

代替

userTeam.teamId=team.id

您对如何解决我的问题有任何想法吗?我会很高兴任何建议和提示。

标签: javascriptpostgresqltypescriptormtypeorm

解决方案


问题已解决。我有反向关系。我应该

@OneToMany(type => UserTeam, userTeam => userTeam.user)
    teams = undefined;

@OneToMany(type => UserTeam, userTeam => userTeam.team)
    users = undefined;

推荐阅读