首页 > 解决方案 > 如何在typeorm和nestjs中检索具有两个条件的数据

问题描述

下面的课是我的桌子

@Entity()
export class Comment extends BaseEntity {

    @PrimaryGeneratedColumn()
    id: number

    @Column()
    body: string

    @Column()
    createdAt: Date

    @Column()
    userId: number

    @Column()
    courseId: number


    @OneToMany(() => Comment, comment => comment.parent, { eager: true })
    children: Comment[];


    @Column({ nullable: true })
    parentId: number

    @ManyToOne(() => Comment, comment => comment.children)
    @JoinColumn({ name: 'parentId' })
    parent: Comment

    @Column()
    status: CommentStatus
}

我想检索parentId等于 null 且coureseId等于45的项目, 但它不起作用,我错在哪里?

public async getCommentsByCourseId(courseId: number): Promise<Comment[]> {
    const query = this.createQueryBuilder('comment')
        .innerJoinAndSelect('comment.children', 'parent')
        .where("comment.parentId IS NULL")
        .andWhere("comment.courseId = :courseId", { courseId: 45 }) // this line does not work 


    const comments = await query.getMany()

    return comments
}

标签: mysqlnestjstypeorm

解决方案


我为一个虚拟实体尝试了以下操作 -

  async getRecordsByUserId(userId: number): Promise<any[]> {
      return await getRepository(DummyEntity)
      .createQueryBuilder('dummyEntity')
      .innerJoinAndSelect('dummyEntity.user', 'user')
      .where("dummyEntity.entity_id IS NULL")
      .andWhere("dummyEntity.userId = :userId", { userId: 1 })
      .getRawMany();
  }

它按预期工作。


推荐阅读