如何使用数据库查询来过滤nodejs中的表行?

问题描述 投票:-1回答:1

我正在为演示应用程序使用nest js framework。在我的演示应用程序中,我有一个entity名称:Category,其中有两个列(id,描述)。描述是jsonb类型

export class Category extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ type: 'jsonb' })
  description;
}

我在表中插入了一些数据。

enter image description here现在我要过滤该数据,只显示那些具有name = test

的行

当前使用下面的代码给我所有行。但是我只需要具有name equals to test的行。当前只有一行

@Get('/app')
  async getApp(): Promise<Category[]> {
    return this.categoryRepository.find({});
  }

这是我的代码https://codesandbox.io/s/nest-nhqyb?file=/src/app.controller.ts:568-670

您可以看到类似的过滤结果

https://nhqyb-5000.sse.codesandbox.io/app

javascript node.js postgresql nestjs typeorm
1个回答
0
投票

根据this issue,除非您正在编写原始SQL并使用数据库特定的语法,否则是不可能的。

在Postgres中,看起来像

SELECT * 
FROM Category cat
WHERE EXISTS (
  SELECT FROM jsonb_each(cat.description) desc
   WHERE  desc.value->>'name' ILIKE 'test'
   );

进行更多讨论,并有深入的答案over here

© www.soinside.com 2019 - 2024. All rights reserved.