Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM load related entities using repository.createQueryBuilder() instead of repository.find()

Tags:

typeorm

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?

like image 236
Daniel Santos Avatar asked Sep 07 '18 21:09

Daniel Santos


2 Answers

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();
like image 113
Daniel Santos Avatar answered Oct 19 '22 01:10

Daniel Santos


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.

like image 1
juzeff Avatar answered Oct 19 '22 01:10

juzeff