Sobes.tech
Junior

How is the "one-to-many" relationship implemented in a database?

sobes.tech AI

Answer from AI

To implement a "one-to-many" relationship in a relational database, a primary key from the "one" table and a foreign key in the "many" tables are used.

The "one" side table (for example, "Departments"):

dept_id (PK) dept_name
1 IT
2 Sales

The "many" side table (for example, "Employees"):

emp_id (PK) emp_name dept_id (FK)
101 Ivan 1
102 Maria 1
103 Petr 2

Here, dept_id in the "Employees" table is a foreign key referencing the primary key dept_id in the "Departments" table. Each department can have many employees, but each employee belongs to only one department.

In Python, using ORM such as SQLAlchemy, it looks like this:

# modules imported

class Department(Base):
    __tablename__ = 'departments'

    id = Column(Integer, primary_key=True) # Primary Key
    name = Column(String)

    # "one-to-many" relationship - One department has many employees
    employees = relationship("Employee", back_populates="department")


class Employee(Base):
    __tablename__ = 'employees'

    id = Column(Integer, primary_key=True) # Primary Key
    name = Column(String)
    department_id = Column(Integer, ForeignKey('departments.id')) # Foreign Key

    # "many-to-one" relationship - Many employees belong to one department
    department = relationship("Department", back_populates="employees")