I have a entity "Transaction" who has a related entity "Customer". I would like to load the customer related to the transaction.
It works like this:
Repository.find({ relations: ['customer'] });
But I want to do a more complex query, So then I use QueryBuilder
Rrepository.createQueryBuilder('t')
.leftJoin( /*...*/ )
.where( /*...*/ })
.getOne();
This returns the transaction with a null
customer.
my Entities are:
@Entity()
export default class Transaction {
...
@ManyToOne(type => Customer, c => c.transactions, { nullable: true, eager: true })
public customer?: Customer;
...
}
and
@Entity()
export default class Customer {
...
@OneToMany(type => Transaction, t => t.customer)
@JoinColumn({ name: 'cust_id', referencedColumnName: 'cust_id' })
public transactions?: Array<Transaction>;
...
}
How can I load the Transaction Customer using the onto a Transaction
object using CreateQueryBuilder
command?
After a lot of tests i found out that loading the relation is simple but I must use leftJoinAndSelect()
function.
context.createQueryBuilder('t')
.leftJoinAndSelect("t.customer", "customer")
.leftJoinAndSelect(/* other joins */)
.where(/* custom where */)
.getOne();
I had similar problem and discovered that there is a difference between:
.leftJoinAndSelect("t.customer", "c")
which loads the related entity under customer attribute of transaction and
.leftJoinAndSelect("customer", "c", "t.cust_id = c.id")
which doesn't refer to the relation - thus does not load it.
Eager on relation doesn't change the outcome of QueryBuilder query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With