我有一个实体“交易”,它有一个相关实体“客户”。 我想加载与交易相关的客户。
它的工作原理如下:
Repository.find({ relations: ['customer'] });
但是我想做一个更复杂的查询,所以我使用QueryBuilder
Rrepository.createQueryBuilder('t')
.leftJoin( /*...*/ )
.where( /*...*/ })
.getOne();
这将返回与 null
客户的交易。
我的实体是:
@Entity()
export default class Transaction {
...
@ManyToOne(type => Customer, c => c.transactions, { nullable: true, eager: true })
public customer?: Customer;
...
}
和
@Entity()
export default class Customer {
...
@OneToMany(type => Transaction, t => t.customer)
@JoinColumn({ name: 'cust_id', referencedColumnName: 'cust_id' })
public transactions?: Array<Transaction>;
...
}
如何使用 CreateQueryBuilder
命令将 Transaction Customer 加载到 Transaction
对象上?
最佳答案
经过大量测试,我发现加载关系很简单,但我必须使用 leftJoinAndSelect()
函数。
context.createQueryBuilder('t')
.leftJoinAndSelect("t.customer", "customer")
.leftJoinAndSelect(/* other joins */)
.where(/* custom where */)
.getOne();
关于TypeORM使用repository.createQueryBuilder()而不是repository.find()加载相关实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52230044/