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
referencesTypically 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
CascadeDelete dependent rows
RestrictBlock delete if dependents exist
SetNullNull out FK
SetDefaultReset FK to default value
NoActionDefer to DB constraint behavior
8. Querying One-to-One Relations
const user = await prisma.user. findUnique ({
where: { id: 1 },
include: { profile: true }
});
Operator Use
includeEmbed related profile
selectSelectively project fields
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
updateModify related record
upsertUpdate if exists else create
disconnectDetach without deletion
deleteRemove the related row