首页 > 解决方案 > TypeORM,ManyToMany 按类别 id 获取帖子(TreeEntity 物化路径)

问题描述

我正在尝试像 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 查询?

标签: typescriptquery-buildertypeorm

解决方案


我刚刚写了一个可能的快速解决方案。我测试了它,它应该可以正常工作。如果没有就回复

@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

希望这可以帮助 :)


推荐阅读