typescript TypeORM选择实体,但某些ID不等于条件的实体除外

juzqafwq  于 2023-03-09  发布在  TypeScript
关注(0)|答案(3)|浏览(331)

我有两个实体:

@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 {我想要什么}
所以,在最后我想得到所有的产品,而不是禁止销售在选定的点。我这样做:

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

但它不起作用(它根本不应该起作用)
我需要帮助正确的请求.谢谢=)
另外,我使用PostgreSQL

z9zf31ra

z9zf31ra1#

我不确定你是否需要使用查询生成器。在这里你可以找到使用关系编写连接的替代方法的描述。
要通过id不等于您提供的id(.where('point.id != :id', {id}))来过滤它们,您可以编写类似find({where: {id: Not(id)}})的代码,其中Not是从TypeORM导入的。

lh80um4z

lh80um4z2#

尝试将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();
vuktfyat

vuktfyat3#

我发现最简单的方法是使用typeormNot运算符,如下所示:

return this.productRepository.find( { where: id: Not('some_id') } );

关于Not的文档:
查找选项运算符。用于对表达式求反。示例:{ title:not(“hello”)}将返回title不等于“hello”的实体。
在此阅读更多信息

相关问题