首页 > 解决方案 > 在 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:未找到实体列“秒”。

也许有人可以帮助我...

谢谢你和最好的问候格雷格

标签: typescriptpostgresqlnestjstypeorm

解决方案


我一直在寻找可以使用我创建的自定义存储库并查询类似于上面示例的内容。我最终不得不做这样的事情:

    primeRepository.createQueryBuilder("prime")
    .innerJoin("prime.seconds", "s")
    .where("s.insertDate >= :startDate and s.insertDate <= :endDate", {startDate: '2020-01-01', endDate: '2020-01-31'})
    .getMany()

上面的示例是我根据您的查询编写的以及我为使其正常工作所做的工作,不确定它是否会下降并“按原样”工作,您可能需要对其进行调整。如果您仍然需要解决方案,我只是想帮助您找到正确的方向。我希望在未来的版本中,他们会解决这个问题并使其更直观。


推荐阅读