How may I define a 3-way relationship as many-to-m...
# orm-help
y
How may I define a 3-way relationship as many-to-many? Suppose I have the following schema: vendors
Copy code
- id
- name
services
Copy code
- id
- name
areas
Copy code
- id
- name
vendors_services_areas
Copy code
- vendor_id
- service_id
- area_id

 @@id([vendor_id, service_id, area_id])
How can this be defined in Prisma Schema and how do I add a new vendor mapped to its two relationships?
r
@Yaakov 👋 Just like a many-to-many relationship b/w 2 models, this will include 3 models like this:
Copy code
model Vendor {
  id   Int    @id @default(autoincrement())
  name String
  vsa  VSA[]
}

model Service {
  id   Int    @id @default(autoincrement())
  name String
  vsa  VSA[]
}

model Area {
  id   Int    @id @default(autoincrement())
  name String
  vsa  VSA[]
}

model VSA {
  vendor   Vendor @relation(fields: [vendorId], references: [id])
  vendorId Int

  service   Service @relation(fields: [serviceId], references: [id])
  serviceId Int

  area   Area @relation(fields: [areaId], references: [id])
  areaId Int

  @@id([vendorId, serviceId, areaId])
}
Inserting a vendor and mapping will be the same using
connect
or
create
for the explicit relation.
y
Thanks @Ryan! How may I then do a
findMany
that will return the data in the following format?
Copy code
"vendors": [
  {
    "name": "Vendor 1",
    "services": [
      {
        "name": "Service 1",
        "areas": [
          {
            "name": "Area 1"
          },
          {
            "name": "Area 2"
          }
        ]
      },
      {
        "name": "Service 2",
        "areas": [
          {
            "name": "Area 1"
          },
          {
            "name": "Area 2"
          }
        ]
      }
    ]
  }
]
r
Services is not related directly to areas in this case, so I don’t think you’ll be able to get the response in this format.
y
@Ryan It seems that the only way to get the above format is by using an
implicit many-to-many
. Is this impossible to achieve using an
explicit many-to-many
, if I don't connect a 3rd relationship?
r
I don’t think so. Implicit many-to-many only works for 2 relations so you would need to create an explicit many-to-many if you’re adding the 3rd one.
y
@Ryan Sorry for not being clear. In my last question I was asking if it is possible to get data in the above format if I only have 2 relations, but define explicitly? Thanks so much!
r
Not currently. The explicit relation object will be included in the output so your data will be nested one level. There’s a feature request for this here so it would be great if you could add a 👍
y
@Ryan Just did! I'm coming from the Laravel/Eloquent world, which is probably why my expectations are so high 😄 On the other hand, the fact that this ORM is so new makes it so much fun! Since the user's input and suggestions are taken into consideration!
🙌 1