惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
Google DeepMind News
Google DeepMind News
Hugging Face - Blog
Hugging Face - Blog
D
Docker
F
Fortinet All Blogs
博客园 - 三生石上(FineUI控件)
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
J
Java Code Geeks
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Simon Willison's Weblog
Simon Willison's Weblog
S
Security Affairs
NISL@THU
NISL@THU
T
Tor Project blog
A
About on SuperTechFans
宝玉的分享
宝玉的分享
腾讯CDC
S
Schneier on Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
P
Privacy & Cybersecurity Law Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Stack Overflow Blog
Stack Overflow Blog
P
Privacy International News Feed
雷峰网
雷峰网
C
Cyber Attacks, Cyber Crime and Cyber Security
Vercel News
Vercel News
Cisco Talos Blog
Cisco Talos Blog
D
DataBreaches.Net
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Google Online Security Blog
Google Online Security Blog
Recorded Future
Recorded Future
L
LINUX DO - 热门话题
Microsoft Security Blog
Microsoft Security Blog
Latest news
Latest news
C
Check Point Blog
有赞技术团队
有赞技术团队
T
The Exploit Database - CXSecurity.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
云风的 BLOG
云风的 BLOG
SecWiki News
SecWiki News
Application and Cybersecurity Blog
Application and Cybersecurity Blog
爱范儿
爱范儿
月光博客
月光博客
V
Vulnerabilities – Threatpost
T
Threat Research - Cisco Blogs
P
Palo Alto Networks Blog
T
The Blog of Author Tim Ferriss
C
Cisco Blogs
Webroot Blog
Webroot Blog
S
Security @ Cisco Blogs

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Prisma relationships, finally explained (with MySQL side by side)
Mohamed Idri · 2026-05-08 · via DEV Community

If Prisma relationships feel like a maze, this post is for you. We are going to build the data model for a small job posting app and walk through every kind of relationship, side by side with MySQL and a quick ER diagram for each one.

You already know MySQL and ER diagrams. The goal here is not to teach you what a foreign key is. The goal is to make Prisma's syntax click so you stop guessing where to put what.

The one idea that fixes everything

Most people get stuck because Prisma asks you to declare a relationship on both models. That looks redundant, like you are saying the same thing twice. You are not.

Here is the rule that unlocks the whole thing:

The foreign key column lives on exactly one side.
Both models name each other so Prisma can see the link in both directions.

In MySQL you only write the foreign key once, on the table that holds it. Prisma still does that, but it also asks the other table to name the relationship from its point of view, just for the JavaScript side. That second declaration does not create any extra column. It is purely so you can write user.jobPostings later in your code.

Keep that in your head as we go.

The app we are building

A simple job posting platform. Three things to track:

  • A User (someone who uses the app)
  • A Profile (extra info about each user, like bio and avatar)
  • A JobPosting (a job a user has posted on the platform)
  • A SavedJob (a job a user has bookmarked)

That gives us all four common shapes of relationship:

Shape In our app
One to one User has one Profile
One to many User has many JobPostings
Many to one JobPosting belongs to one User (same thing)
Many to many Users save many JobPostings, jobs are saved by many Users

Let us build them one at a time.


1. One to many (and many to one)

This is the most common shape. A user posts many jobs. Each job belongs to one user.

ER picture

┌────────┐ 1        N ┌─────────────┐
│  User  │───────────>│ JobPosting  │
└────────┘            └─────────────┘

Enter fullscreen mode Exit fullscreen mode

The arrow goes from User (the "one" side) to JobPosting (the "many" side).

MySQL version

CREATE TABLE User (
  id    INT PRIMARY KEY AUTO_INCREMENT,
  name  VARCHAR(255) NOT NULL,
  email VARCHAR(255) NOT NULL UNIQUE
);

CREATE TABLE JobPosting (
  id      INT PRIMARY KEY AUTO_INCREMENT,
  title   VARCHAR(255) NOT NULL,
  salary  INT,
  userId  INT NOT NULL,
  FOREIGN KEY (userId) REFERENCES User(id)
);

Enter fullscreen mode Exit fullscreen mode

The foreign key sits on JobPosting. That is the "many" side. There is no column on User that points to jobs. Users do not need to know who their jobs are. The jobs know who their user is.

Prisma version

model User {
  id           Int          @id @default(autoincrement())
  name         String
  email        String       @unique
  jobPostings  JobPosting[]
}

model JobPosting {
  id      Int    @id @default(autoincrement())
  title   String
  salary  Int?
  user    User   @relation(fields: [userId], references: [id])
  userId  Int
}

Enter fullscreen mode Exit fullscreen mode

Notice three things:

  1. The real column is userId on JobPosting. That is the foreign key, and it is exactly the same column you wrote in MySQL.
  2. user User @relation(...) does not create a column. It is a "relation field" that tells Prisma "this userId points to a User, and I want to call it .user in code".
  3. jobPostings JobPosting[] on User does not create a column either. It is the back reference. It exists so you can write user.jobPostings to fetch them.

So one foreign key in the database, two relation fields in the schema. One per model.

What @relation(fields: [userId], references: [id]) actually says

Read it as a sentence:

"The user field on this model is connected via my userId column, which references the id column on User."

You only put @relation(fields, references) on one side, the side that holds the foreign key. The other side just gets a bare JobPosting[] (or JobPosting for one to one) with no @relation attribute, because there is nothing to declare there.

Querying it

// All jobs posted by user 1
const jobs = await prisma.jobPosting.findMany({
  where: { userId: 1 },
});

// A user with their jobs included
const user = await prisma.user.findUnique({
  where: { id: 1 },
  include: { jobPostings: true },
});

// Create a job for an existing user
await prisma.jobPosting.create({
  data: {
    title: "Junior Developer",
    salary: 40000,
    user: { connect: { id: 1 } },
  },
});

Enter fullscreen mode Exit fullscreen mode

connect is how you say "use an existing user, do not create a new one". It is one of the most useful pieces of the Prisma syntax once you spot it.


2. One to one

A user has one extended profile. The profile belongs to exactly one user.

ER picture

┌────────┐ 1        1 ┌─────────┐
│  User  │───────────>│ Profile │
└────────┘            └─────────┘

Enter fullscreen mode Exit fullscreen mode

MySQL version

CREATE TABLE Profile (
  id      INT PRIMARY KEY AUTO_INCREMENT,
  bio     TEXT,
  avatar  VARCHAR(255),
  userId  INT NOT NULL UNIQUE,
  FOREIGN KEY (userId) REFERENCES User(id)
);

Enter fullscreen mode Exit fullscreen mode

Same as one to many, with one extra trick: UNIQUE on userId. That constraint is what turns "many to one" into "one to one". Without it, multiple profiles could point at the same user.

Prisma version

model User {
  id      Int      @id @default(autoincrement())
  name    String
  email   String   @unique
  profile Profile?
}

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

Enter fullscreen mode Exit fullscreen mode

Two changes from one to many:

  1. profile Profile? instead of Profile[]. Singular, not a list. The ? means "optional", which fits real life: users may or may not have a profile yet.
  2. @unique on userId. Same job as MySQL. It enforces "at most one profile per user". Without @unique, Prisma would treat this like one to many.

The shape on the back reference (Profile? vs Profile[]) is what tells Prisma whether you want one to one or one to many. The @unique at the database level is what enforces it.

Querying it

const userWithProfile = await prisma.user.findUnique({
  where: { id: 1 },
  include: { profile: true },
});

// Create a user and their profile in one go
await prisma.user.create({
  data: {
    name: "Bob",
    email: "bob@example.com",
    profile: {
      create: { bio: "I write code", avatar: "bob.png" },
    },
  },
});

Enter fullscreen mode Exit fullscreen mode

That nested create is one of Prisma's nicest features. Two tables, one call, one transaction.


3. Many to many

Users can save jobs they like. Each user saves many jobs. Each job can be saved by many users.

In MySQL you handle this with a join table. In Prisma you have two choices: implicit (Prisma builds the join table for you) or explicit (you build it yourself). We will look at the explicit one because it matches MySQL exactly and gives you room to add extra fields later, which you almost always end up wanting.

ER picture

┌────────┐ 1   N ┌──────────┐ N   1 ┌─────────────┐
│  User  │──────>│ SavedJob │<──────│ JobPosting  │
└────────┘       └──────────┘       └─────────────┘

Enter fullscreen mode Exit fullscreen mode

A many to many is really just two one to many relationships meeting in the middle.

MySQL version

CREATE TABLE SavedJob (
  userId        INT NOT NULL,
  jobPostingId  INT NOT NULL,
  savedAt       TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (userId, jobPostingId),
  FOREIGN KEY (userId) REFERENCES User(id),
  FOREIGN KEY (jobPostingId) REFERENCES JobPosting(id)
);

Enter fullscreen mode Exit fullscreen mode

The SavedJob table holds two foreign keys and uses both together as the primary key. That guarantees a user cannot save the same job twice.

Prisma version

model User {
  id           Int          @id @default(autoincrement())
  name         String
  email        String       @unique
  jobPostings  JobPosting[]
  savedJobs    SavedJob[]
}

model JobPosting {
  id            Int         @id @default(autoincrement())
  title         String
  salary        Int?
  user          User        @relation(fields: [userId], references: [id])
  userId        Int
  savedBy       SavedJob[]
}

model SavedJob {
  user          User        @relation(fields: [userId], references: [id])
  userId        Int
  jobPosting    JobPosting  @relation(fields: [jobPostingId], references: [id])
  jobPostingId  Int
  savedAt       DateTime    @default(now())

  @@id([userId, jobPostingId])
}

Enter fullscreen mode Exit fullscreen mode

A few things to notice:

  1. SavedJob is just a regular model. It has its own fields, including the two foreign keys. It is the join table from MySQL, written as a Prisma model.
  2. @@id([userId, jobPostingId]) is the composite primary key. Same effect as PRIMARY KEY (userId, jobPostingId) in MySQL.
  3. Both User and JobPosting get a SavedJob[] field, because both can be on the "one" side of a one-to-many that points at SavedJob.

This explicit version is more typing than the implicit one, but it gives you the savedAt timestamp for free, and it maps one to one to what your MySQL brain already expects.

Querying it

// User 1 saves job 7
await prisma.savedJob.create({
  data: {
    userId: 1,
    jobPostingId: 7,
  },
});

// All jobs user 1 has saved, with the job details
const saved = await prisma.savedJob.findMany({
  where: { userId: 1 },
  include: { jobPosting: true },
});

// Unsave: delete the join row
await prisma.savedJob.delete({
  where: {
    userId_jobPostingId: { userId: 1, jobPostingId: 7 },
  },
});

Enter fullscreen mode Exit fullscreen mode

That userId_jobPostingId syntax is how Prisma exposes composite primary keys to your code. The two field names get joined with an underscore.


The cheat sheet

Here is the whole picture in one table. Save this and refer back to it.

Shape "Many" side has FK? Back reference type Notes
One to many Yes (the many side) Model[] Most common shape
One to one Yes, with @unique Model? The @unique is the magic
Many to many Both FKs in a join model JoinModel[] on each side Explicit gives you extra fields

And the schema rules:

  • @relation(fields, references) lives on the side with the foreign key.
  • The other side gets a bare relation field with no @relation attribute.
  • [Model] means "many of these". Model? means "optional one of these". Model (no symbol) means "exactly one".

What about deletes? onDelete

Real apps need to decide what happens to job postings when a user is deleted. MySQL has ON DELETE CASCADE and friends. Prisma has the same idea, written like this:

user User @relation(fields: [userId], references: [id], onDelete: Cascade)

Enter fullscreen mode Exit fullscreen mode

The options are:

Option What it does
Cascade Delete the children when the parent is deleted
SetNull Set the foreign key to null on the children
Restrict Refuse to delete if children exist (default)
NoAction Like Restrict, with subtle DB level differences
SetDefault Set FK to its default value on the children

For our app: if you want deleting a user to also delete all their job postings, you would write onDelete: Cascade on the JobPosting.user relation. That mirrors MySQL exactly.

Mental model in two sentences

The foreign key lives on one side, the side with the @relation(fields, references) attribute. The other side just names the relationship so you can navigate to it in code.

Many to many is just two one to manys meeting at a join model, exactly like a join table in MySQL.

If those two sentences feel right, you have the whole picture. Everything else, the connect, the include, the composite keys, is just syntax sugar on top.

A tiny exercise

Open your own schema and try to answer these three questions for each relation you have:

  1. Which side has the actual foreign key column?
  2. What is the back reference type on the other side (Model, Model?, or Model[])?
  3. Should this delete cascade, or do I want it to fail loudly?

If you can answer all three for every relation, your model is in good shape. The job posting app we just built is a good template to come back to whenever you start a new project and need a reminder of how to wire things up.