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 } } }); // ??
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
QueryBuilder
you can join themconst article = await connection
.getRepository(ArticleEntity)
.createQueryBuilder("articles")
.leftJoinAndSelect("articles.tags", "tags")
.where({ id: articleId })
.getMany();
console.log(article.tags);