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
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.
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