【问题标题】:How to find if two arrays contain any common item in SQL? With one array being my set result and the other a list of 'ids'?如何查找两个数组是否包含 SQL 中的任何公共项?一个数组是我的设置结果,另一个是“ids”列表?
【发布时间】:2021-10-08 23:26:03
【问题描述】:

这是我的实体目前的样子:

类别实体

@Entity('category')
export class Category extends BaseEntity {
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @Column({ type: 'text', unique: true })
  name: string;

  @Column({ type: "text", unique: true })
  @Index()
  slug: string;

  @ManyToMany(() => Listing, (listing) => listing.categories, { cascade: true, onDelete: 'CASCADE' })
  listings?: Listing[];

}

上市实体

@Entity('listing')
export class Listing extends BaseEntity {

  @PrimaryGeneratedColumn("uuid")
  id: string;

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

}

查询 1(我目前正在使用的)

这就是我的查询目前的样子:

const listings = await connection.getRepository()
      .createQueryBuilder('listing')
      .distinct(true)
      .leftJoinAndSelect('listing.categories', 'category', 'category.slug IN (:...slugs)', {slugs: [ 'mens-shirts', 'clearance' ]})
      .getMany()

查询 1 个结果

[] // an empty list of Listings (Type: Listing[])

查询 2(检查 innerJoinAndSelect 是否正常工作)

const listings = await connection.getRepository()
        .createQueryBuilder('listing')
        .distinct(true)
        .innerJoinAndSelect('listing.categories', 'category')
        .getMany();

查询 2 结果

[
  Listing {
    id: 'c24ea98d-da53-4f14-8706-a3597f3ee4d1',
    categories: [ [Category], [Category] ]
  },
  Listing {
    id: 'e8b3e680-85b6-4701-9ad7-bf65de348e76',
    categories: [ [Category], [Category] ]
  },
  Listing {
    id: '1bb04ea0-8435-44d6-856f-8eb53f24e941',
    categories: [ [Category], [Category] ]
  },
  Listing {
    id: '0735142d-fd38-4fad-b5a7-0356373dd0a3',
    categories: [ [Category], [Category] ]
  },
]

innerJoinAndSelect 方法正在运行并返回结果,我知道为什么在使用第一个查询时会得到一个空数组。这是因为我试图在类别数组上找到字段slug,而不是数组中的每个类别。

问题: 如何使用 TypeORM 的 QueryBuilder 在类别数组(类型:Category[])中搜索 slug 名称 [ 'mens-shirts', 'clearance' ]?或者我如何检查类别字段中的每个类别是否有一个 slug,即在 [ 'mens-shirts', 'clearance' ] 中。有可能吗?

【问题讨论】:

    标签: sql typescript postgresql orm typeorm


    【解决方案1】:

    搜索元素是否在数组中时,需要使用= ANY()。所以把'category.slug IN (:...slugs)'改成'category.slug = ANY(:slugs)'(注意你不需要在ANY里面使用“spread”,直接引用数组就行了)

    【讨论】:

      猜你喜欢
      • 2011-01-16
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 2022-01-09
      • 2017-05-30
      • 2020-06-24
      • 1970-01-01
      • 2023-03-24
      相关资源
      最近更新 更多