TypeORM findOne with nested relations

Viewed 8961

I am having some issues performing a nested find query with TypeORM. Here's the basic code:

    const { completionId } = req?.params;
    const user = req.user;

    const retrievedCompletion = await getRepository(
      CompletionGoogleSearch
    ).findOne({
      relations: ['run', 'run.user'],
      where: {
        id: completionId,
        // run: { user: { id: user.id } }, // This is the code that breaks the function
      },
    });

    console.log(retrievedCompletion?.run.user.id);
    console.log(user.id);

It looks to me like there's nothing out of order, and that the query should run. Any idea on what I am doing wrong? I know I can get around this issue by writing a querybuilder query or using raw SQL–I am just curious to understand if there's a flaw in my code.

3 Answers

The feature you're asking about doesn't supported on typeorm yet (Feb 2021).

Checkout this issue that was opened on 2018.

the Solution is use eager:true in run.user entity :

  @OneToOne(() => User, User=> User.run, {
    eager:true
  })
  user: User;

and next time you search in CompletionGoogleSearch do just relations: ['run'] and user will come with it.

typeorm added the ability to use nested object

userRepository.find({
  relations: {
    profile: true,
    photos: true,
    videos: {
      videoAttributes: true,
    },
  },
});

on this way, you can fetch the data without using eager.

You can find more information here

Related