mysql - TypeORM leftjoin 具有相同的列名
问题描述
环境
- 类型ORM
- 打字稿
- 表达
- 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 中加入两个表。
如何根据团队列连接两个表?
解决方案
您需要更新实体类,如下所示:
@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();
}
查看此文档以获取更多信息。
推荐阅读
- c++ - 将 OpenCV Mat 转换为“位掩码”
- flutter - Flutter 应用程序音频播放器不播放 url src
- swift - 如何从模态呈现的视图控制器返回到选定的选项卡栏视图控制器?
- python - 如何使鼠标在给定时间范围内平滑过渡到新的相对位置
- groovy - 使用 binding.variables 创建的 SimpleTemplate 在转换为 String 时终止执行
- powershell - Powershell 将访客用户添加到启用邮件的安全组
- windows - 获取短期文件的内容
- r - 为什么“surv.svm”在 R 的“mlr3proba”包中显示错误?
- databricks - 所有笔记本单元格均已取消且没有错误
- javascript - AWS GreenGrass 版本 2 JavaScript 控制台日志不可用