简体   繁体   中英

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?

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.

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