【发布时间】: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