Search code examples
node.jstypeorm

How find entities by many to many relation entity id


I have tags and articles entities that linked by many to many. How can I find tags if I know article id?

@Entity("articles")
class ArticleEntity {
  @ManyToMany(() => TagEntity, tag => tag.articles)
  @JoinTable()
  tags: TagEntity[];
}

@Entity("tags")
class TagEntity {
  @ManyToMany(() => ArticleEntity, article => article.tags)
  articles: ArticleEntity[];
}

const articleId = 1;
this.tagRepo.find({ where: { articles: { id: articleId } } }); // ??

Solution

    1. To load articles with tags you must specify relation in FindOptions
    const articleId = 1;
    const article = await connection.getRepository(ArticleEntity)
                 .findOne(articleId, {relations: ["tags"]});
    
    console.log(article.tags); // contains all tags related to the article.id = 1
    
    1. Using QueryBuilder you can join them
    const article = await connection
        .getRepository(ArticleEntity)
        .createQueryBuilder("articles")
        .leftJoinAndSelect("articles.tags", "tags")
        .where({ id: articleId })
        .getMany();
    
    console.log(article.tags);