首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeORM,ManyToMany按类别id获取帖子(TreeEntity物化-路径)

TypeORM,ManyToMany按类别id获取帖子(TreeEntity物化-路径)
EN

Stack Overflow用户
提问于 2020-06-02 06:26:52
回答 1查看 2.2K关注 0票数 3

我试着像CMS一样按类别发布帖子。

例如,按类别分类的查询帖子A将包括所有附加在“类别A”上的帖子,以及附加到“类别A”的子类的帖子。

我真的不知道如何构建这个查询,所以任何帮助都是非常感谢的:)。

这是我的实体:

代码语言:javascript
复制
@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;
}
代码语言:javascript
复制
export class Post{
   @PrimaryGeneratedColumn()
    id: number;

    @Column()
    title: string;

    @ManyToMany((type) => Category, (category) => category.posts)
    @JoinTable()
    categories: Category[];
}

下面的SQL查询执行此任务(例如,类别id 1)

代码语言:javascript
复制
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查询?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-05 13:02:49

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

代码语言:javascript
复制
@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

希望这会有所帮助:)

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62146087

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档