Hi, just starting out with Prisma. Is it possible ...
# orm-help
n
Hi, just starting out with Prisma. Is it possible to model a one-to-one relationship with the same PK in both tables? The examples in docs produce a FK in one table pointing to a PK in another.
r
@Naresh Bhatia 👋 Do you mean more than a single one-to-one relationship pointing to the same PK?
n
Hi @Ryan, I meant a single one-to-one relation which would generate something like this:
Copy code
CREATE TABLE "User" (
    id SERIAL PRIMARY KEY
);
CREATE TABLE "Profile" (
    id SERIAL PRIMARY KEY,
    FOREIGN KEY ("id") REFERENCES "User"(id)
);
So the User table entry might look like: id: "a12-b23-c45", name: "John Smith" and the corresponding profile entry might look like: id: "a12-b23-c45", picture: "https://....." In other words, the PK on both tables has the same value.
Hi @Ryan, digging deeper what if I write my schema like this:
Copy code
model User {
  id           String  @id @default(uuid())
  name         String
}

model Profile {
  id        String    @id
  picture   String
}
and use it like this:
Copy code
// Create a User
const user = prisma.user.create({
  data: { name: 'John Smith' }
})

// Create a profile for the user
// Note that profile.id = user.id
const profile = prisma.profile.create({
  data: { id: user.id, picture: 'https://...' }
})
Is there any downside to this approach? Of course, I am not telling Prisma that there is a one-to-one relationship. So maybe the query to fetch a user's profile will be more complicated.
r
Yes the fetching will be more complicated. Why not use a foreign key type approach directly instead. That would make it much easier.
✅ 1