首页 > 解决方案 > TypeORM leftjoin 具有相同的列名

问题描述

环境

  1. 类型ORM
  2. 打字稿
  3. 表达
  4. MySQL 5.7

MySQL 数据库中的“TeamSpeed”表

团队 剩下
1 40 60 120
2 50 40 70
3 35 10 80
4 70 15 97

MySQL 数据库中的“TeamWords”表

团队 剩下
1 “去1” “好吧好吧” “左1”
2 “我们走吧” “对2” “左2”
3 “开始了” “对3” “左100”
4 “移动” “对4” “好的左”

类型ORM实体

@Entity('team_speeds')
class Speeds extends BaseEntity {
  @PrimaryGeneratedColumn()
  team: number

  @Column()
  go: number

  @Column()
  right: number

  @Column()
  left: number
}


@Entity('team_words')
class Words extends BaseEntity {
  @PrimaryGeneratedColumn()
  team: number

  @Column()
  go: string

  @Column()
  right: string

  @Column()
  left: string
}

问题

我知道如何在 MySQL Query 中加入两个表。

但是,我不知道如何在 TypeORM 中加入两个表。

如何根据团队列连接两个表?

标签: mysqltypeorm

解决方案


您需要更新实体类,如下所示:

@Entity('team_speeds')
class Speeds extends BaseEntity {
  @PrimaryGeneratedColumn()
  team: number

  @Column()
  go: number

  @Column()
  right: number

  @Column()
  left: number

  @OneToOne(() => Words, words => words.Speeds)
  words: Words;
}


@Entity('team_words')
class Words extends BaseEntity {
  @PrimaryGeneratedColumn()
  team: number

  @Column()
  go: string

  @Column()
  right: string

  @Column()
  left: string

  @OneToOne(() => Speeds, speeds => speeds.words)
  @JoinColumn({ name: 'team' })
  speeds: Speeds;
}

然后当你想查询数据时,你可以使用下面的一个。

1.使用查找:

async foo(teamSpeedId: number) {
  const speeds = await getManager().getRepository(Speeds).find({
    relations: ['words'],
    where: { team: teamSpeedId },
  });
}

2. 使用查询生成器:

async foo(teamSpeedId: number) {
  const speeds = await connection
    .getRepository(Speeds)
    .createQueryBuilder("speed")
    .leftJoinAndSelect("speed.words", "word")
    .where('team = :id', {id: teamSpeedId})
    .getMany();
}

查看此文档以获取更多信息。


推荐阅读