Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Harsh Mishra
Harsh Mishra

Posted on

     

Understanding Relationships in MySQL and Prisma

Understanding Relationships in MySQL and Prisma

Introduction

In relational databases like MySQL, defining relationships between tables is essential for structuring data efficiently. There are three main types of relationships:One-to-One (1:1),One-to-Many (1:M), andMany-to-Many (M:N). Each type requires a specific table structure, foreign key constraints, and query approach.

In this article, we will explore:

  • How to define relationships in MySQL with SQL table schemas.
  • How to query related data using SQL.
  • How to model the same relationships inPrisma ORM.
  • How to retrieve related data using Prisma queries.

By the end, you’ll have a solid understanding of how to manage relational data efficiently withMySQL and Prisma. 🚀

1. Types of Relations in MySQL

In MySQL, relationships between tables are typically categorized into three main types:

  1. One-to-One (1:1)
  2. One-to-Many (1:M)
  3. Many-to-Many (M:N)

For each relation, I will explain:

  • Table Schema in MySQL
  • Querying the Relationship in SQL
  • How to Define It in Prisma Schema
  • Querying the Relationship in Prisma
  • Example Output

2. One-to-One (1:1) Relationship

Example Scenario

AUser can haveone Profile, and aProfile belongs to only oneUser.

MySQL Table Schema

CREATETABLEusers(idINTAUTO_INCREMENTPRIMARYKEY,nameVARCHAR(255)NOTNULL);CREATETABLEprofiles(idINTAUTO_INCREMENTPRIMARYKEY,bioTEXT,user_idINTUNIQUE,-- Ensures one-to-one relationshipFOREIGNKEY(user_id)REFERENCESusers(id)ONDELETECASCADE);
Enter fullscreen modeExit fullscreen mode

Querying in MySQL (Fetching User with Profile)

SELECTusers.id,users.name,profiles.bioFROMusersLEFTJOINprofilesONusers.id=profiles.user_id;
Enter fullscreen modeExit fullscreen mode

Example Output

idnamebio
1JohnLoves coding
2AliceEnjoys music

Defining One-to-One in Prisma Schema

model User {  id      Int      @id @default(autoincrement())  name    String  profile Profile?}model Profile {  id     Int    @id @default(autoincrement())  bio    String?  user   User   @relation(fields: [userId], references: [id])  userId Int    @unique}
Enter fullscreen modeExit fullscreen mode

Querying in Prisma

constuserWithProfile=awaitprisma.user.findMany({include:{profile:true}});console.log(userWithProfile);
Enter fullscreen modeExit fullscreen mode

Example Output in Prisma

[{"id":1,"name":"John","profile":{"bio":"Loves coding"}},{"id":2,"name":"Alice","profile":{"bio":"Enjoys music"}}]
Enter fullscreen modeExit fullscreen mode

3. One-to-Many (1:M) Relationship

Example Scenario

AUser can havemany Posts, but eachPost belongs to only oneUser.

MySQL Table Schema

CREATETABLEusers(idINTAUTO_INCREMENTPRIMARYKEY,nameVARCHAR(255)NOTNULL);CREATETABLEposts(idINTAUTO_INCREMENTPRIMARYKEY,titleVARCHAR(255),contentTEXT,user_idINT,FOREIGNKEY(user_id)REFERENCESusers(id)ONDELETECASCADE);
Enter fullscreen modeExit fullscreen mode

Querying in MySQL (Fetching User with Posts)

SELECTusers.id,users.name,posts.titleFROMusersLEFTJOINpostsONusers.id=posts.user_id;
Enter fullscreen modeExit fullscreen mode

Example Output

idnametitle
1JohnMySQL Guide
1JohnPrisma Intro
2AliceMusic Life

Defining One-to-Many in Prisma Schema

model User {  id    Int     @id @default(autoincrement())  name  String  posts Post[]}model Post {  id      Int    @id @default(autoincrement())  title   String  content String?  user    User   @relation(fields: [userId], references: [id])  userId  Int}
Enter fullscreen modeExit fullscreen mode

Querying in Prisma

constusersWithPosts=awaitprisma.user.findMany({include:{posts:true}});console.log(usersWithPosts);
Enter fullscreen modeExit fullscreen mode

Example Output in Prisma

[{"id":1,"name":"John","posts":[{"title":"MySQL Guide","content":"MySQL is great!"},{"title":"Prisma Intro","content":"Prisma is awesome!"}]},{"id":2,"name":"Alice","posts":[{"title":"Music Life","content":"I love music"}]}]
Enter fullscreen modeExit fullscreen mode

4. Many-to-Many (M:N) Relationship

Example Scenario

AStudent can enroll inmany Courses, and aCourse can havemany Students.

MySQL Table Schema

CREATETABLEstudents(idINTAUTO_INCREMENTPRIMARYKEY,nameVARCHAR(255)NOTNULL);CREATETABLEcourses(idINTAUTO_INCREMENTPRIMARYKEY,titleVARCHAR(255)NOTNULL);CREATETABLEenrollments(student_idINT,course_idINT,PRIMARYKEY(student_id,course_id),FOREIGNKEY(student_id)REFERENCESstudents(id)ONDELETECASCADE,FOREIGNKEY(course_id)REFERENCEScourses(id)ONDELETECASCADE);
Enter fullscreen modeExit fullscreen mode

Querying in MySQL (Fetching Students with Courses)

SELECTstudents.name,courses.titleFROMenrollmentsJOINstudentsONenrollments.student_id=students.idJOINcoursesONenrollments.course_id=courses.id;
Enter fullscreen modeExit fullscreen mode

Example Output

nametitle
JohnMath 101
JohnPhysics 201
AliceMath 101

Defining Many-to-Many in Prisma Schema

model Student {  id         Int       @id @default(autoincrement())  name       String  courses    Course[]  @relation("Enrollments")}model Course {  id         Int       @id @default(autoincrement())  title      String  students   Student[] @relation("Enrollments")}model Enrollment {  student   Student @relation(fields: [studentId], references: [id])  studentId Int  course    Course  @relation(fields: [courseId], references: [id])  courseId  Int  @@id([studentId, courseId])}
Enter fullscreen modeExit fullscreen mode

Querying in Prisma

conststudentsWithCourses=awaitprisma.student.findMany({include:{courses:true}});console.log(studentsWithCourses);
Enter fullscreen modeExit fullscreen mode

Example Output in Prisma

[{"name":"John","courses":[{"title":"Math 101"},{"title":"Physics 201"}]},{"name":"Alice","courses":[{"title":"Math 101"}]}]
Enter fullscreen modeExit fullscreen mode

5. Summary Table

RelationshipMySQL SchemaSQL QueryPrisma SchemaPrisma Query
One-to-Oneuser_id UNIQUE in second tableJOIN ON user_idUser has Profile?include: { profile: true }
One-to-ManyForeign key in child tableJOIN ON user_idUser has Post[]include: { posts: true }
Many-to-ManyJunction table with two FKsJOIN through junctionStudent[] - Course[]include: { courses: true }

Conclusion

  • MySQL usesforeign keys andjunction tables to define relationships.
  • Prisma uses adeclarative schema to simplify relationship management.
  • Querying relationships in Prisma is easy usinginclude.
  • Output in Prisma is structured as JSON, making it easy to work with.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Aspiring Software Developer | Tech Enthusiast | Skilled in HTML, CSS, JavaScript, Node.js, Express.js, React | Enthusiastic about Data Science and ML (NumPy, Pandas, scikit-learn) and DevOps tools.
  • Joined

More fromHarsh Mishra

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp