我正在尝试像 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 查询?
最佳答案
我刚刚写了一个可能的快速解决方案。我测试了它,它应该可以正常工作。如果没有就回应
@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[];
}
此方法使用查询生成器 https://github.com/typeorm/typeorm/issues/2135#issuecomment-388801132
以及 findDescendants 函数 https://typeorm.io/#/tree-entities
希望这有帮助:)
关于typescript - TypeORM, ManyToMany 按类别 id (TreeEntity 物化路径) 获取帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62146087/