如何在typeorm多对多关系中选择特定列

aRt*_*too 4 typescript typeorm typeorm-activerecord

我与 TYPEORM 中的自定义联接表有 n:m 关系。

实体1

@Entity({ name: 'users' })
export class User extends BaseModel {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column({ type: 'varchar', length: 50 })
  @IsNotEmpty()
  username!: string;

  @Column({ unique: true, type: 'varchar', length: 50 })
  @IsEmail()
  @IsNotEmpty()
  email!: string;

  @CreateDateColumn({ type: 'timestamp' })
  createdAt!: Date;

  @UpdateDateColumn({ type: 'timestamp' })
  updatedAt!: Date;

  @DeleteDateColumn({ type: 'timestamp' })
  deletedAt!: Date;

  @OneToMany(
    (type) => UsersGameGroup,
    (userGameGroup) => userGameGroup.user,
    { cascade: true }
  )
  usersGameGroups!: UsersGameGroup[];
}
Run Code Online (Sandbox Code Playgroud)

实体2

@Entity({ name: 'game_groups' })
export class GameGroup extends BaseModel {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column()
  title!: string;

  @OneToMany(
    (type) => UsersGameGroup,
    (userGameGroup) => userGameGroup.gameGroup,
    { cascade: true }
  )
  usersGameGroups!: UsersGameGroup[];
}

Run Code Online (Sandbox Code Playgroud)

Entity3 一个连接表

@Entity({ name: 'users_game_groups' })
export class UsersGameGroup extends BaseModel {
  @PrimaryGeneratedColumn()
  id!: number;

  @Column({ type: 'int' })
  userId!: number;

  @Column({ type: 'int' })
  gameGroupId!: number;

  @ManyToOne(
    (type) => User,
    (user) => user.usersGameGroups,
    { onDelete: 'CASCADE' }
  )
  user!: User;

  @ManyToOne(
    (type) => GameGroup,
    (gameGroup) => gameGroup.usersGameGroups,
    { onDelete: 'CASCADE' }
  )
  gameGroup!: GameGroup;
}
Run Code Online (Sandbox Code Playgroud)

我正在查询gameGroup以获取用户。

const gg = await GameGroup.findOneOrFail(gameGroupID, {
        select: ['id', 'title'],
        relations: ['usersGameGroups', 'usersGameGroups.user']
      });
const { id, title, createdAt, updatedAt, usersGameGroups } = gg;
Run Code Online (Sandbox Code Playgroud)

但这里的问题是它将返回用户的所有列。我想要的只是username.

返回样本:

{
  "meta": {},
  "payload": {
    "gameGroup": {
      "id": 2,
      "title": "game2",
      "users": {
        "id": 2,
        "title": "game2",
        "usersGameGroups": [
          {
            "id": 2,  <-this too I don't need this but whatever
            "userId": 1, <-this too I don't need this but whatever
            "gameGroupId": 2, <-this too I don't need this but whatever
            "createdAt": "2020-04-09T00:11:39.000Z", <-this too I don't need this but whatever
            "updatedAt": null, <-this too I don't need this but whatever
            "deletedAt": null, <-this too I don't need this but whatever
            "user": {
              "id": 1,
              "username": "new1",
              "email": "new1@gmail.com", <- I just need this
              "createdAt": "2020-04-09T00:09:45.000Z",
              "updatedAt": "2020-04-09T00:10:55.000Z",
              "deletedAt": null
            }
          },
          {
            "id": 3, <-this too I don't need this but whatever
            "userId": 2, <-this too I don't need this but whatever
            "gameGroupId": 2, <-this too I don't need this but whatever
            "createdAt": "2020-04-09T00:12:10.000Z", <-this too I don't need this but whatever
            "updatedAt": null, <-this too I don't need this but whatever
            "deletedAt": null, <-this too I don't need this but whatever
            "user": {
              "id": 2,
              "username": "new2", <- I just need this
              "email": "new2@gmail.com",
              "createdAt": "2020-04-09T00:09:51.000Z",
              "updatedAt": null,
              "deletedAt": null
            }
          }
        ]
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我这样查询。我包括user及其用户名,例如user.username

relations: ['usersGameGroups', 'usersGameGroups.user', 'user', 'user.username']
Run Code Online (Sandbox Code Playgroud)

我收到一个错误。

"Relation \"user\" was not found, please check if it is correct and really exist in your entity."
Run Code Online (Sandbox Code Playgroud)

在原始 SQL 中,查询看起来像这样。

"Relation \"user\" was not found, please check if it is correct and really exist in your entity."
Run Code Online (Sandbox Code Playgroud)

我期待这样的 JSON 响应。

SELECT
    u.username
FROM 
    users u
JOIN 
    users_game_groups ugg
ON ugg.userId = u.id
JOIN 
    game_groups gg
ON gg.id = ugg.gameGroupId
WHERE gg.id = 2;
Run Code Online (Sandbox Code Playgroud)

谢谢你!!<3

aRt*_*too 5

经过反复试验、阅读实际代码库和充分的不放弃,我终于得到了答案。

const foo = await GameGroup.createQueryBuilder()
        .select(['gg.title', 'gg.id', 'ugg.id', 'u.username', 'u.email'])
        .from(GameGroup, 'gg')
        .innerJoin('gg.usersGameGroups', 'ugg')
        .innerJoin('ugg.user', 'u')
        .where({ id: gameGroupID })
        .getOne();
Run Code Online (Sandbox Code Playgroud)

但我希望它使用活动记录。

就像是:

const gg = await GameGroup.findOneOrFail(gameGroupID, {
        select: ['id', 'title', 'createdAt', 'updatedAt', 'usersGameGroups'],
        join: {
          alias: 'gg',
          innerJoinAndSelect: { ugg: 'gg.usersGameGroups', u: 'ugg.user' }
        }
});
Run Code Online (Sandbox Code Playgroud)

但我无法从这里选择:我不能这样做gg.usersGameGroups