Working with One-to-One Relations
1. Defining One-to-One Relation
model User {
id Int @id @default(autoincrement())
profile Profile?
}
model Profile {
id Int @id @default(autoincrement())
bio String
userId Int @unique
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
| Rule | Detail |
|---|---|
| Unique FK | @unique on the FK side enforces 1:1 |
| Owner side | Holds @relation and FK |
2. Setting Foreign Key Field
| Aspect | Detail |
|---|---|
| Type | Must match referenced field type |
| Naming | relatedModelId convention |
| Constraint | Index automatically created |
3. Configuring Referenced Field
| Option | Detail |
|---|---|
references | Typically points to id |
| Non-PK | Allowed if column is @unique |
4. Using Optional One-to-One Relations
| Pattern | Effect |
|---|---|
| Both sides optional | Profile can exist without user (set userId Int?) |
| Parent side | Always optional in Prisma (profile Profile?) |
5. Creating Required One-to-One Relations
await prisma.user.create({
data: {
email: "a@b.io",
profile: { create: { bio: "Hello" } }
}
});
| Tip | Detail |
|---|---|
| Required FK | Must create child in same call or supply connect |
6. Setting Relation Name
| Why | Detail |
|---|---|
| Disambiguation | Required when 2+ relations between same models |
| Syntax | @relation("authoredBy", fields:[...], references:[...]) |
7. Using Referential Actions
| Action | onDelete Behavior |
|---|---|
Cascade | Delete dependent rows |
Restrict | Block delete if dependents exist |
SetNull | Null out FK |
SetDefault | Reset FK to default value |
NoAction | Defer to DB constraint behavior |
8. Querying One-to-One Relations
const user = await prisma.user.findUnique({
where: { id: 1 },
include: { profile: true }
});
| Operator | Use |
|---|---|
include | Embed related profile |
select | Selectively project fields |
9. Creating Related Records
| Operation | Syntax |
|---|---|
| Nested create | profile: { create: { bio } } |
| Connect existing | profile: { connect: { id: 5 } } |
| Connect-or-create | profile: { connectOrCreate: {...} } |
10. Updating One-to-One Relations
await prisma.user.update({
where: { id: 1 },
data: {
profile: {
upsert: {
create: { bio: "New" },
update: { bio: "Updated" }
}
}
}
});
| Action | Effect |
|---|---|
update | Modify related record |
upsert | Update if exists else create |
disconnect | Detach without deletion |
delete | Remove the related row |