TypeORM选择实体(某些实体除外,其中id不等于条件)

时间:2020-02-21 10:15:16

标签: typescript typeorm

我有两个实体:

    @Entity()
    export class Point {
    
         @PrimaryGeneratedColumn('uuid')
         id: string;
    
         // some other stuff
 
    }


    @Entity()
    export class Product {
    
         @PrimaryGeneratedColumn('uuid')
         id: string;
    
         @IsOptional()
         @ManyToMany(() => Point)
         @JoinTable()
         prohibitedToSaleOn: Point[];
    
    }

我想获取产品,其中prohibitedToSaleOnPoint的数组)中的任何对象都满足条件

point.id!= {idWhatIWant}

因此,最后我想获得所有产品,而不是在选定的位置禁止销售的产品。我这样做:

    return this.productRepository.createQueryBuilder('product')
        .leftJoin('product.prohibitedToSaleOn', 'point')
        .where('point.id != :id', {id})
        .getMany();

但是它不起作用(根本不应该)

我需要有关正确请求的帮助。谢谢=)

P.S。我使用PostgreSQL

2 个答案:

答案 0 :(得分:0)

尝试将WHERE条件移至join级别

return this.productRepository.createQueryBuilder('product')
        .leftJoin('product.prohibitedToSaleOn', 'point', 'point.id != :id', {id})
        .getMany();

此查询应返回prohibitedToSaleOn连接表中包含的所有产品,但指定的点ID除外。

如果您需要在选定时间点未被禁止销售的产品和从未被禁止的产品,则需要这样的查询:

return this.productRepository.createQueryBuilder('product')
        .leftJoin('product.prohibitedToSaleOn', 'point', '(point.id != :id OR point.id IS NULL)', {id})
        .getMany();

答案 1 :(得分:0)

我不确定是否需要使用查询生成器。 Here可以找到使用关系编写联接的另一种方法的说明。

要通过不等于您提供的ID(.where('point.id != :id', {id}))来过滤ID,可以编写类似find({where: {id: Not(id)}})的代码,其中Not是从TypeORM导入的。