Hey all. I need help with multiple relationships b...
# orm-help
p
Hey all. I need help with multiple relationships between the same tables. Imagine this scenario: I have “Plug” model and “Signal” like this:
Copy code
model Plug {
  id               Int       @id @default(autoincrement())
  // other fields, then...
  latest_signal_id Int?      @unique
  latestSignal     Signal?   @relation(fields: [latest_signal_id], references: [id])
  signals          Signal[]
}

// Then the Signal model:

model Signal {
  id             Int       @id @default(autoincrement())
  plug_id        Int
  plug           Plug      @relation(fields: [plug_id], references: [id])

  tag_id         Int
  @@unique([plug_id, tag_id], name: "plug_signals_plug_id_tag_id_unique")
}
As you can see, in “Plug” model I want to have TWO relationships with the Signal model. One of then is: “A Plug has a LIST of Signal, the “signals” relationship”. Then the second one: “Signal have a direct pointer to the “latest” Signal. This “latest signal” is defined by the “latest_signal_id” column in Plug model. I’m getting the following errors from VSCode Prisma plugin:
Copy code
Error validating model "Plug": Ambiguous relation detected. The fields `latestSignal` and `signals` in model `Plug` both refer to `Signal`. Please provide different relation names for them by adding `@relation(<name>).
How can I have this kind of “two relationships” at the same time? What am I doing wrong here? Because I put that
@relation(fields: [latest_signal_id], references: [id])
in front of prop
latestSignal
but it didn’t work.
r
@Pedro Paulo Almeida 👋 You need to specify a relation name like this:
Copy code
model Plug {
  id               Int      @id @default(autoincrement())
  // other fields, then...
  latest_signal_id Int      @unique
  latestSignal     Signal   @relation("latestSignal", fields: [latest_signal_id], references: [id])
  signals          Signal[] @relation("signals")
}

// Then the Signal model:

model Signal {
  id      Int   @id @default(autoincrement())
  plug_id Int
  plug    Plug  @relation("signals", fields: [plug_id], references: [id])
  latest  Plug? @relation("latestSignal")

  tag_id Int
  @@unique([plug_id, tag_id], name: "plug_signals_plug_id_tag_id_unique")
}
Have a look at this doc for why this is needed.