Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

TarikAli's avatar

multi levels relationship

Hello, i have a university db

faculties

each faculty has sections

each section has certificates ( Master's, Ph.D )

each certificate has semesters

each semester has subjects

each subject has lessons

can i make a table link all these tables like :

table study_plane :

id, faculty_id, section_id, certificate_id, semester_id, subject_id

or it's bad practice ?

is there a good schema for such this multi levels ?

Thanks

Thanks

0 likes
1 reply
LaryAI's avatar
Level 58

The proposed solution of creating a table called "study_plane" with columns for each level of the hierarchy is a valid approach. However, it may lead to a large number of null values in the table if not all levels are present for a particular record. Another approach is to use a hierarchical data model, such as a nested set or a closure table. This would allow for more efficient querying of the data and easier management of the hierarchy.

Here is an example of how to implement a closure table for this scenario:

  1. Create a table called "sections" with columns for "id" and "name".
  2. Create a table called "section_closure" with columns for "ancestor_id" and "descendant_id".
  3. Insert a record into "sections" for each section in the university.
  4. For each section, insert a record into "section_closure" with the "ancestor_id" and "descendant_id" set to the section's "id".
  5. For each section, insert a record into "section_closure" for each of its ancestors (i.e. the faculty it belongs to).
  6. Repeat steps 3-5 for the remaining levels of the hierarchy (certificates, semesters, subjects, and lessons).

To query the data, you can join the relevant tables together using the closure table. For example, to get all lessons in a particular faculty:

SELECT lessons.*
FROM faculties
JOIN section_closure ON section_closure.descendant_id = faculties.id
JOIN sections ON sections.id = section_closure.ancestor_id
JOIN section_closure AS certificate_closure ON certificate_closure.ancestor_id = sections.id
JOIN certificates ON certificates.id = certificate_closure.descendant_id
JOIN section_closure AS semester_closure ON semester_closure.ancestor_id = certificates.id
JOIN semesters ON semesters.id = semester_closure.descendant_id
JOIN section_closure AS subject_closure ON subject_closure.ancestor_id = semesters.id
JOIN subjects ON subjects.id = subject_closure.descendant_id
JOIN section_closure AS lesson_closure ON lesson_closure.ancestor_id = subjects.id
JOIN lessons ON lessons.id = lesson_closure.descendant_id
WHERE faculties.id = ?

Please or to participate in this conversation.