Kevvv
Kevvv

Reputation: 4023

GraphQL Prisma database that allows two tables to have relations to one table

I'm looking to have relational tables that connects two different tables to the one table.

type User {
  booking: [Booking!]! @relation(name: "UserToBooking" onDelete: SET_NULL)
}

type Booking {
  owner: User! @relation(name: "UserToBooking", onDelete: SET_NULL)
  renter: [User!]! @relation(name: "UserToBooking", onDelete: SET_NULL)
}

Prisma only allows one of the same relation so having two "UserToBooking" is not possible. What's the best way to create a relation that allows to do this?

Upvotes: 0

Views: 318

Answers (1)

Andrew1325
Andrew1325

Reputation: 3579

You'd have to have two different booking types. I'm guessing this is something like an AirBnB arrangement where a user can own a property that is rented out and/or also rent properties from others. I think you should specify two different items in your User type to distinguish these, and then have a relationship for these. Something like this:

type User {
  booking: [Booking!]! @relation(name: "UserToBooking" onDelete: CASCADE)
  let: [Booking!]! @relation(name: "UserToLetBooking" onDelete: CASCADE)
}

type Booking {
  owner: User! @relation(name: "UserToLetBooking", onDelete: SET_NULL)
  renter: User! @relation(name: "UserToBooking", onDelete: SET_NULL)
}

This way the booking shows a user who is the letting owner and a user who is the renter. I have also changed the renter in booking to a single user because I figure each booking has 1 letting owner and 1 renter. I also changed the onDelete setting for the user type so that if a user is deleted any of his bookings or lets are also deleted. This would be a typical pattern but is up to you.

Upvotes: 1

Related Questions