如何在Prisma ORM中按关联关系过滤:匹配部分属性即可返回
Prisma 一对多关联属性过滤方案
问题描述
现有Car与Attribute一对多关联模型,需要过滤关联属性值。原查询使用every约束,仅当attributes数组中所有值都匹配关联Attribute的typeCar数组时,才返回对应Car记录(若有任何属性不匹配则无结果)。现在需要调整逻辑:只要Car关联的Attribute的typeCar数组与attributes有任意交集,就返回该Car记录,无需满足所有属性都存在。
原查询代码(不符合需求):
const attributes = ["Car", "Bike", "Truck"] prisma.car.findMany({ where: { attribute: { typeCar: { every: { value: { hasSome: attributes }, }, }, }, }, });
数据模型
model Car { id String @id name String status String description String thumbnailUrl String? groupId String? categoryName String attribute Attribute[] images CarImage[] createdAt DateTime @default(now()) updatedAt DateTime? @updatedAt @@map("car") } model Attribute { id String @id typeCar String[] car Car? @relation(fields: [carId], references: [id]) carId String? createdAt DateTime @default(now()) updatedAt DateTime? @updatedAt @@map("attributeProductValue") }
解决方案
将原查询中的every替换为some,并修正属性匹配逻辑(直接针对typeCar数组做hasSome判断),即可实现“只要有任意属性匹配就返回Car记录”的需求:
const attributes = ["Car", "Bike", "Truck"] prisma.car.findMany({ where: { attribute: { // 只要Car关联的任意一个Attribute的typeCar数组包含attributes中的至少一个值 some: { typeCar: { hasSome: attributes, }, }, }, }, });
逻辑说明
some:表示Car关联的Attribute集合中,存在至少一个满足后续条件的记录即可typeCar: { hasSome: attributes }:判断该Attribute的typeCar数组与目标attributes数组存在交集(即包含至少一个相同元素)
内容的提问来源于stack exchange,提问作者wiliamvj
相关产品推荐
相关产品推荐

