Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM: Load relations with only certain specified fields

Despite much research and trial and error, I unfortunately do not yet have an elegant solution for the following use case: A user has several posts, which is correctly implemented as a one-to-many relationship. I want to load the user with all his posts, but not all attributes of the posts, only certain ones.

Approach 1: Find

await this.usersRepository.find({relations: ['posts']});

Here I can't define a corresponding select restriction anywhere.

Approach 2: QueryBuilder

await this.usersRepository.createQueryBuilder('user')
.leftJoinAndSelect('user.posts', 'posts').select('posts.title').getMany();

Here I define the restriction supposedly, but the select seems to refer only to user.

Am I missing something? Or is there no intended solution for my use case?

I would be very grateful for help, thanks guys!

TypeORM version 0.2.22

like image 827
stoniemahonie Avatar asked May 30 '26 09:05

stoniemahonie


1 Answers

I was able to get the appropriate results you're expecting. You don't have to use getRawMany if you don't want to, and need the nested objects like I do from getMany and getManyAndCount in the way my schema is built up.

That being said, if you have the correct OneToMany relation setup in your entity

@OneToMany(type => Post, post => post.user)
posts: Post

Then you should be able to hit

const userResults: any = await getRepository(entities.User)
    .createQueryBuilder('user')
    .leftJoinAndSelect('user.posts', 'posts')
    .select([
        'posts.name',
        'user.id'
    ])
    .getMany()

Which results in

userResults User {
  id: 3,
  posts: [ Post { name: 'asdfasdfasdf' }, Post { name: 'asdf' } ] }

Hope this helps, and/or you figured this out.

like image 131
sh on Avatar answered Jun 02 '26 21:06

sh on



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!