Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Relations

The one rule that explains everything

The foreign key lives on the “many” side.

A user has many posts. So Post holds userId, not the other way around. Once that clicks, all four shapes are easy.

One-to-many

model User {
    id    Int    @id @default(autoincrement())
    posts Post[]                       // ← no @relation needed
}

model Post {
    id     Int  @id @default(autoincrement())
    userId Int  @map("user_id")
    user   User @relation(fields: [userId], references: [id], onDelete: Cascade)
}

Notice the asymmetry:

  • Post.user declares fields / references because it owns the FK.
  • User.posts declares nothing — Zyvor infers it from the other side.

Generated:

SideRust fieldSQL column
User.postsVec<PostModel>none
Post.userIdi32user_id
Post.userOption<Arc<UserModel>>none

SQL: user_id INTEGER REFERENCES users(id) ON DELETE CASCADE.

Model-typed fields produce zero columns. They’re navigation, not data.

Many-to-one

Same declaration, read from the other direction. Post.user is the many-to-one. No separate syntax to learn.

One-to-one

Add @unique to the FK, and ? on the parent side:

model User {
    id      Int          @id @default(autoincrement())
    profile UserProfile?              // ← optional, singular
}

model UserProfile {
    id     Int  @id @default(autoincrement())
    userId Int  @unique               // ← the whole trick
    user   User @relation(fields: [userId], references: [id], onDelete: Cascade)
}

@unique means at most one profile row per user. ? means a user may have none.

Generated: User.profile is Option<Arc<UserProfileModel>>.

Verified output — user 1 has a profile, user 2 doesn’t:

[
  { "id": 1, "profile": { "id": 1, "website": "https://zyvor.dev" } },
  { "id": 2, "profile": null }
]

Many-to-many

Both sides declare through, pivotFrom, pivotTo:

model Post {
    id   Int   @id @default(autoincrement())
    tags Tag[] @relation(through: "post_tags", pivotFrom: "post_id", pivotTo: "tag_id")
}

model Tag {
    id    Int    @id @default(autoincrement())
    posts Post[] @relation(through: "post_tags", pivotFrom: "tag_id", pivotTo: "post_id")
}

Read it as: “from me, my pivot column is pivotFrom; the other side’s column is pivotTo.” They mirror each other.

⚠️ camelCase: pivotFrom, pivotTo — not pivot_from.

Generated: Vec<Arc<TagModel>> on both sides.

You must declare the pivot table yourself

Zyvor does not invent a join table from through:. Declare it as a model:

model PostTag {
    id     Int @id @default(autoincrement())
    postId Int @map("post_id")
    tagId  Int @map("tag_id")

    post Post @relation(fields: [postId], references: [id], onDelete: Cascade)
    tag  Tag  @relation(fields: [tagId],  references: [id], onDelete: Cascade)

    @@unique([postId, tagId])
    @@map("post_tags")
}

Six extra lines, and you get a real CREATE TABLE, real foreign keys, and a composite unique constraint that makes ON CONFLICT DO NOTHING work.

Verified: Rust → 2 posts, ORM → 1 post, resolved through post_tags.

onDelete

ValueMeaning
Cascadedelete children with the parent
Restrictblock the delete if children exist
SetNullset the FK to NULL (field must be nullable)
NoActiondefer to the database

Cascade on Post.userId means deleting a user removes their posts — verified end-to-end.

Three consequences to know before you query

1. Nothing loads automatically

posts is [] until you call .with(User::posts). There’s no lazy loading either — touching the field never triggers a query. See Eager Loading.

2. Back-references don’t serialize

Zyvor marks back-references #[serde(skip)] to prevent infinite recursion (Post → User → Posts → …). Side effect: a loaded Post.user is invisible in raw model JSON. Use DTOs — the Axum guide shows the pattern.

3. with_nested needs a collection

Nested eager loading requires a Vec-shaped relation:

#![allow(unused)]
fn main() {
.with_nested(User::posts, |q| q.with(Post::comments))   // ✓ posts is a Vec
.with_nested(Post::user,  |q| q.with(User::posts))      // ✗ won't compile
}

For a single relation, use plain .with(Post::user).

Not supported yet

GapDetail
Composite foreign keysmulti-column fields / references parses, but codegen handles single-column only
Auto-generated pivot tablesdeclare the pivot model
Full cardinality validationsome invalid shapes slip through the validator
Scalar arraystags String[] is not a relation and is rejected by CRUD generation

Next: Migrations.