如何在typeorm多对多关系中选择特定列 [英] How to select a specific column in typeorm many to many relationship

查看:109
本文介绍了如何在typeorm多对多关系中选择特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an n:m relationship with a custom join table in TYPEORM.

实体 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 一个连接表

Entity3 a Join table

@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 以获取用户.

and I'm querying gameGroup to get the users.

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

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

but the problem here is it will return all the columns of the user. All I want is the 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

And if I query it like this. I include the user and its username like 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 中,查询看起来像这样.


In raw SQL the query looks something like this.

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 响应.


I'm expecting a JSON response like this.

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

谢谢!!<3

推荐答案

啊,终于在试错之后,阅读实际的代码库和大量的不放弃我终于得到了答案.

Ahh finally after trial and error, reading the actual codebase and a full amount of not giving up I finally got an answer.

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

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

but I want it using active record.

类似:

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

但我不能从这里选择.我不能做 gg.usersGameGroups 叹息 :(

but I cant select from here though. I cant do gg.usersGameGroups sigh :(

这篇关于如何在typeorm多对多关系中选择特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆