typescript - 在 find() 中 TypeORM 查询相关的 oneToMany 值
问题描述
我有以下 SQL 查询,我想用 ORM 映射替换它:
SELECT primeid, name
FROM primes p INNER JOIN seconds s ON s.primeid = p.primeid
WHERE s.insertdate >= '2020-01-01 and s.insertdate <= '2020-01-31'
我有以下实体:
@Entity("primes")
export class PrimeEntity {
@PrimaryColumn({name:'primeid'})
primeId: number;
@Column()
name: string;
@OneToMany('SecondEntity','prime')
seconds: SecondEntity[];
}
@Entity("seconds")
export class SecondEntity {
@PrimaryColumn({name:'secondid'})
secondId: number;
@Column({name: 'insertdate'})
insertDate: Date;
@ManyToOne('PrimeEntity', 'seconds')
@JoinColumn('primeid')
prime: PrimeEntity;
}
以下代码应返回与开头的 SQL 查询几乎相同的内容:
primeRepository.find({
relations: ['seconds'],
where: {
seconds: {
insertDate: Between('2020-01-01', '2020-01-31')
}
}
});
它应该返回
[
PrimeEntity {primeId: 1, name: 'test', seconds: [SecondEntity {secondId: 1, insertDate: '2020-01-01'}]},
...
]
但相反,我收到以下错误消息:
EntityColumnNotFound:未找到实体列“秒”。
也许有人可以帮助我...
谢谢你和最好的问候格雷格
解决方案
我一直在寻找可以使用我创建的自定义存储库并查询类似于上面示例的内容。我最终不得不做这样的事情:
primeRepository.createQueryBuilder("prime")
.innerJoin("prime.seconds", "s")
.where("s.insertDate >= :startDate and s.insertDate <= :endDate", {startDate: '2020-01-01', endDate: '2020-01-31'})
.getMany()
上面的示例是我根据您的查询编写的以及我为使其正常工作所做的工作,不确定它是否会下降并“按原样”工作,您可能需要对其进行调整。如果您仍然需要解决方案,我只是想帮助您找到正确的方向。我希望在未来的版本中,他们会解决这个问题并使其更直观。
推荐阅读
- django - 自动调用django函数
- php - 试图用php发布多维数组
- c - 检查宏返回的变量返回条件始终为假
- autodesk-viewer - 如何获取所有模型元素的 dbId?
- android - 登录webview中Android空白页面上的MS OAuth2 - 如果我破坏配置,它将在webview中显示错误并工作
- sql - SQL Server 表计算到特殊列
- java - 正则表达式匹配直到Java中的文本结尾
- linux - 使用 gcc/ld/cmake 链接到特定的 .so 版本,拒绝其他版本
- batch-file - Windows 10 批处理文件:在以前版本中工作的文件的奇怪行为
- gcc - 汇编代码生成 SEGMENTATION FAULT