[FIXED] How to select fields from joined table using TypeORM repository?

Issue

I have 2 models with one-to-many connection – Post and User:

entities/post.entity.ts
@Entity()
export class Post {
  ...
  @ManyToOne(() => User, (user) => user.posts) user: User;
}

entities/user.entity.ts
@Entity()
export class User {
  ...
  @OneToMany(() => Post, (post) => post.user) posts: Post[];
}

To get data from database I use repositories, and my question is – how can I get only userId field from this query.

constructor(
  @InjectRepository(Post) private postRepository: Repository<Post>
) {}

findAll(): Promise<Post[]> {
  return this.postRepository.find({
    relations: ['user']
  });
}

Now response looks like this:

{
    "id": 1,
    "title": "Nam fringilla volutpat venenatis. Nulla et sem.",
    "content": "Aliquam tr...",
    "preview": "p1",
    "createdAt": "2022-08-28T11:52:44.833Z",
    "updatedAt": "2022-08-28T11:52:44.833Z",
    "user": {
      "id": 1,
      "firstName": "Timber",
      "lastName": "Saw",
      "createdAt": "2022-08-28T11:52:44.827Z",
      "updatedAt": "2022-08-28T11:52:44.827Z"
    }
  },

Cause now I just get the whole entity, but I want only id of user. I know, I can use createQueryBuilder, but is it possible to do using repositories?

Solution

According to the documentation, this one might help you:

this.postRepository.find({
    relations: {
      user: true
    },
    select: {
      user: {
        id: true
      }
    }
  });

For reference: https://orkhan.gitbook.io/typeorm/docs/find-options

Answered By – Dimi Vi

Answer Checked By – Katrina (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published