Sobes.tech
Junior

What types of relationships between models in a database do you know?

sobes.tech AI

Answer from AI

  • One-to-One
  • Many-to-One
  • Many-to-Many

One-to-One

Each instance of one entity is linked to exactly one instance of another entity, and vice versa.

For example, User and Profile. Each user can have only one profile, and each profile belongs to only one user.

Many-to-One

Multiple instances of one entity are linked to a single instance of another entity.

For example, Article and Author. Each author can have many articles, but each article is written by only one author.

Many-to-Many

Multiple instances of one entity are linked to multiple instances of another entity.

For example, Student and Course. Each student can have many courses, and each course can have many students.

Implementing a Many-to-Many relationship usually requires creating an intermediate table.

-- Example structure for Many-to-Many relationship between Student and Course

-- Table for students
CREATE TABLE students (
    student_id INT PRIMARY KEY,
    name VARCHAR(100)
);

-- Table for courses
CREATE TABLE courses (
    course_id INT PRIMARY KEY,
    title VARCHAR(100)
);

-- Intermediate table for Student and Course relationship
CREATE TABLE student_courses (
    student_course_id INT PRIMARY KEY,
    student_id INT,
    course_id INT,
    FOREIGN KEY (student_id) REFERENCES students(student_id),
    FOREIGN KEY (course_id) REFERENCES courses(course_id)
);