简体   繁体   中英

How to filter by relationships using each Prisma orm

I have a one to many relationship, and I need to filter the relationship values, I need to bring all the records that contain all the values of the array/

example: const attributes = ["Car", "Bike", "Truck"]

prisma.car.findMany({
  where: {
    attribute: {
      typeCar: {
        every: {
          value: { hasSome: attributes },
        },
      },
    },
  },
});

This search works only if all attributes exist, if any attribute does not exist, nothing is returned

I need it to return the record, even if typeCar does not contain all records.

How could I do that with the prisma?

My model

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")
}

One solution I found was to add a new field in the car table. Saving the values of the typeCar

model Car {
  id            String     @id
  name          String
  status        String
  description   String
  thumbnailUrl  String?
  groupId       String?
  categoryName  String
  attribute     Attribute[]
  images        CarImage[]
  typeCarValues String[]
  createdAt     DateTime   @default(now())
  updatedAt     DateTime?  @updatedAt

  @@map("car")
}

So I can filter without going through the relationship, and the hasEvery option works.

example: const attributes = ["Car", "Bike", "Truck"]

prisma.car.findMany({
  where: {
    typeCarValues: {
      hasEvery: attributes,
    },
  },
})

The problem was in filtering the relationship in attributes using every and then hasEvery , to return the value all attributes of typeCar need to be informed and exist, if any of them is not informed, it does not return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM