Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM findOne with nested relations

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.

like image 841
Francesco S Avatar asked Sep 11 '25 02:09

Francesco S


1 Answers

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

like image 128
Yoav St Avatar answered Sep 13 '25 16:09

Yoav St