You are on page 1of 5

In Prisma, establishing a one-to-one

relation between two models involves


defining a field in one model that
references the primary key of the other
model. Here's a simple example using
two models, `User` and `Profile`,
where each user has one profile:

1. Define your Prisma schema


(`schema.prisma`):

```prisma
// schema.prisma

model User {
id Int @id
@default(autoincrement())
username String @unique
email String @unique
profile Profile? @relation(fields:
[profileId], references: [id])
profileId Int?
}

model Profile {
id Int @id
@default(autoincrement())
bio String
user User @relation(fields:
[userId], references: [id])
userId Int @unique
}
```

2. Run `prisma generate` to generate


the Prisma client.

3. Use the Prisma client in your code


to interact with the database. For
example, creating a user with a profile:

```javascript
const { PrismaClient } =
require('@prisma/client');

const prisma = new PrismaClient();

async function main() {


// Create a user with a profile
const userWithProfile = await
prisma.user.create({
data: {
username: 'john_doe',
email: 'john@example.com',
profile: {
create: {
bio: 'Hello, I am John Doe.'
}
}
},
// Include the profile data in the
response
include: {
profile: true
}
});

console.log('User with profile:',


userWithProfile);
}

main()
.catch((e) => {
throw e;
})
.finally(async () => {
await prisma.$disconnect();
});
```

In this example, the `User` model has


a nullable `profileId` field that
references the `id` field in the `Profile`
model. Conversely, the `Profile` model
has a required `userId` field that
references the `id` field in the `User`
model. This establishes a one-to-one
relationship between `User` and
`Profile`.

You might also like