【问题标题】:How to select a specific column in typeorm many to many relationship如何在typeorm多对多关系中选择特定列
【发布时间】:2020-04-09 03:42:33
【问题描述】:

我与 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[];
}

实体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[];
}

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

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

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

但这里的问题是它会返回用户的所有列。我想要的只是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
            }
          }
        ]
      }
    }
  }
}

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

relations: ['usersGameGroups', 'usersGameGroups.user', 'user', 'user.username']

我收到一个错误。

"Relation \"user\" was not found, please check if it is correct and really exist in your entity."

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

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;

我期待这样的 JSON 响应。

"gameGroup": {
      "id": 2,
      "title": "game2",
      "users": {
        "id": 2,
        "title": "game2",
        "usersGameGroups": [
          {
            "user": {
              "username": "new1",
            }
          },
            "user": {
              "username": "new2",
            }
          }
        ]
      }
    }

谢谢!!

【问题讨论】:

    标签: typeorm typeorm-activerecord


    【解决方案1】:

    啊啊啊终于经过反复试验,阅读了实际的代码库并全力不放弃我终于得到了答案。

    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();
    

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

    类似:

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

    但我不能从这里选择。我不能gg.usersGameGroups叹气:(

    【讨论】:

      猜你喜欢
      • 2014-08-21
      • 2021-10-18
      • 1970-01-01
      • 2021-12-26
      • 2014-09-01
      • 2020-06-29
      • 2020-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多