我试着像CMS一样按类别发布帖子。
例如,按类别分类的查询帖子A将包括所有附加在“类别A”上的帖子,以及附加到“类别A”的子类的帖子。
我真的不知道如何构建这个查询,所以任何帮助都是非常感谢的:)。
这是我的实体:
@Tree("materialized-path")
export class Category {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@ManyToMany((type) => Post, (post) => post.categories)
posts: Post[];
@Expose()
@TreeChildren()
children: Category[];
@Expose()
@TreeParent()
parent: Category;
}export class Post{
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@ManyToMany((type) => Category, (category) => category.posts)
@JoinTable()
categories: Category[];
}下面的SQL查询执行此任务(例如,类别id 1)
SELECT * FROM post WHERE id IN (
SELECT postId FROM post_categories_category as postCat WHERE postCat.categoryId IN (
SELECT id FROM category WHERE category.mpath LIKE "1.%" OR category.mpath LIKE "%.1.%"
)
)因此,问题是,如何将此SQL查询转换为typeORM查询?
发布于 2020-06-05 13:02:49
我刚写了一个可能的快速解决方案。我测试过了它应该能正常工作。如果没有,就回答
@Entity()
@Tree("materialized-path")
export class Category extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@ManyToMany((type) => Post, (post) => post.categories)
posts: Post[];
@TreeChildren()
children: Category[];
@TreeParent()
parent: Category;
async getPosts(): Promise<Post[]> {
const categories = await getConnection().getTreeRepository(Category).findDescendants(this); // gets all children
categories.push(this); // adds parent
const ids = categories.map(cat => cat.id) // get an array of ids
return await Post.createQueryBuilder('post')
.distinct(true) // dont get duplicates (posts in two categories)
.innerJoin('post.categories', 'category', 'category.id IN (:...ids)', {ids}) // get posts where category is in categories array
.innerJoinAndSelect('post.categories', 'cat') // add all categories to selected post
.orderBy('post.id')
.getMany()
}
}
@Entity()
export class Post extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@ManyToMany((type) => Category, (category) => category.posts)
@JoinTable()
categories: Category[];
}此方法使用querybuilders https://github.com/typeorm/typeorm/issues/2135#issuecomment-388801132。
以及findDescendants函数https://typeorm.io/#/tree-entities
希望这会有所帮助:)
https://stackoverflow.com/questions/62146087
复制相似问题