这是我的实体当前的样子:
类别实体
@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();
查询结果
[
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
,而不是数组中的每个类别。
问题:我将如何搜索段名称[ 'mens-shirts', 'clearance' ]
,在类别(类型:Category[]
)的数组中,使用TypeORM的QueryBuilder?或者我如何检查类别字段中的每个类别是否有一个slug,即[ 'mens-shirts', 'clearance' ]
。这可能吗?
在搜索元素是否在数组内时需要使用= ANY()
。所以把'category.slug IN (:...slugs)'
改成'category.slug = ANY(:slugs)'
(注意你不需要使用"spread")在ANY
内部,直接引用数组)