Hello :slightly_smiling_face: I'm finally trying o...
# orm-help
f
Hello 🙂 I'm finally trying out Prisma2, looks really nice so far 😄 I have a question about data modeling, I would like to have a model A referring to 0, 1 or 2 rows of model B, I tried something like this but with no success:
Copy code
model A {
  id String @id

  // A can exist without B
  mainB   B?      @relation(name: "AB", fields: [mainBID], references: [id])
  mainBID String?

  secondB   B?      @relation(name: "AB", fields: [secondBID], references: [id])
  secondBID String?
}

enum BType {
  MAIN
  SECOND
}

model B {
  id    String @id
  type  BType

  // B must be attached to an A to exist
  a   A       @relation(name: "AB", fields: [aID], references: [id])
  aID String

  @@unique([type, aID])
}
Am I forced to do a 1-m relation (ie. replace
mainB
and
secondB
with
bs  B[]
in
model A
) or is it possible to achieve something like this? Even when I tried to add names to the relations it was still ambiguous for prisma :( Something I didn't try but I think would look terrible, is to completely separate the 1-1 relations (i'd like to refer to A from B without needing to check
type
to know which key to include in the query + I need to make sure B is linked to an A), ie.
Copy code
model A {
  id String @id

  mainB   B? @relation(name: "MainAB")
  secondB B? @relation(name: "SecondAB")
}

enum BType {
  MAIN
  SECOND
}

model B {
  id    String @id
  type  BType

  mainA   A?  @relation(name: "MainAB", fields: [mainAID], references: [id])
  mainAID String?

  secondA   A?  @relation(name: "SecondAB", fields: [secondAID], references: [id])
  secondAID String?
}
If you have any suggestion I'd be happy to hear ^^
r
@Florian 👋 I think a 1-many relationship would be better in this case as you’re not sure how many items of
B
would
A
be related to.
This would also make it simpler to query for and see if the specific relation you want is present instead of having 2 separate 1-1 optional relations.
f
Yea that's what I ended up doing, I feel like 2 optional 1-1 would be the worst ^^ So no possibility to have 2 optional references to B in A, while B has 1 mandatory reference to A (I realize I forgot to add
mainBID  String?
and
secondBID  String?
in my first example)?
r
That’s not possible unfortunately.
f
Ok thanks!
👍 1