Search code examples
expresstypeorm

When i use leftJoinAndSelect in Typeorm, There is an error not to use the table more than once


win10, latest express, latest typeorm

@EntityRepository(Post)
export class PostRepository extends AbstractRepository<Post> {
  findPostById(postId: number) {
    return this.createQueryBuilder('post')
      .leftJoinAndSelect('post.user', 'user')
      .leftJoinAndSelect('post.postComments', 'postComment')
      .leftJoinAndSelect('postComment.user', 'user')
      .leftJoinAndSelect('post.likes', 'like')
      .leftJoinAndSelect('post.dislikes', 'dislike')
      .where('post.id = :postId', { postId })
      .getOne();
  }
} 

If i use a above, i will get the following error

The table name "user" is specified at least once.

.leftJoinAndSelect('post.user', 'user')
.leftJoinAndSelect('postComment.user', 'user')

How can I resolve this situation?


Solution

  • You are getting an error because you are using the alias user for more than one join - post.user and postComment.user.

    Try something like .leftJoinAndSelect('postComment.user', 'postCommentUser').

    Now if for example you want to select the user id of the user who made the post, you can specify that by user.id. If you wanted to select the id of the user who commented on the post, you can specify that by postCommentUser.id