Typeorm Find condition for related entity

Viewed 9452

I have two entities, a User and a Post entity. A user can have multiple posts.

I would like to find a post based on the post title and the name of the author like this:

const post = await postsRepository.find({
  where: {
    title: postTitle,
    user: {
      name: userName,
    },
  },
  relations: ['user'],
});

Typeorm generates the following SQL:

SELECT `Post`.`id` AS `Post_id`, `Post`.`title` AS `Post_title`, `Post`.`user_id`
AS `Post_user_id`, `Post__user`.`id` AS `Post__user_id`, `Post__user`.`name` AS
`Post__user_name` FROM `posts` `Post` LEFT JOIN `users` `Post__user` ON
`Post__user`.`id`=`Post`.`user_id` WHERE (`Post`.`user_id` = ?) -- PARAMETERS: [null]

As you can see, it is not querying the name attribute at all.

But it doesn't work and I can't find anything in the documentation.

[Edit]: On the other hand, the following code works as expected but isn't using joins to query the relation:

const user = await usersRepository.findOne({ name: userName });
const post = await postsRepository.find({
  where: {
    title: postTitle,
    user: {
      id: user.id,
    },
  },
  relations: ['user'],
});

[/Edit]

The only thing I could was something like this

const post = await postsRepository.createQueryBuilder('posts')
  .innerJoinAndSelect('posts.user', 'user')
  .where({
    title: postTitle,
  })
  .andWhere('user.name = :name', { name: userName })
  .getOne();

So this works but tbh it looks super shitty and is pretty annoying to write when you need to filter by additional relations.

Is there anything I have missed in the documentation?

0 Answers
Related