How to code many-to-many relationships?

I got confused (mentally) connecting databases and object-oriented programming.

Imagine an application for teachers, for example, with a user interface that displays students in a row of a table and assignments in columns. The base database may include many-to-many relationships: the student has many assignments, and the assignment has many students.

How does the base code work? Do you have a Student class with a variable that references a list of assignments? Or an assignment class with a variable referring to the list of students? Both that and another? ... Do you have some StudentAssignment class connecting instances of Student and Assignment? (And if so, does this mean that a class with 50 students and 10 assignments simultaneously has 500 StudentAssignment objects, 50 Student objects and 10 Assignment objects?) ... And then these different classes consist mainly of (for example) SQL statements working with a database?

I know a lot of questions here, but they all go together ... what is a common many-to-many coding strategy?

ps Just so that you do not think that I am lazy, I looked at other questions, for example How to model many, many relationships in the code? and Modeling manyToMany relationships with attributes .

+3
source share
2 answers

In the database, you need the student table, destination table, and StudentAssignment intersection table. Representation of the PLO can consist only in the fact that each student has a collection of his assignments. Do you need to know that students have a specific task? If you do, then in any case, fill out this information in the Assignment objects. Or, you can also check each student for a specific assignment. It depends on you.

, , .

StudentAssignment. , .

EDIT:

, , , , 50 10 . , ( ).

, :

( 50 ), Assignments emty.

SELECT
    StudentName,
    ID
FROM
    Student

( 10 ), .

SELECT
    AssignmentName,
    ID
FROM
    Assignment

, - : (, , 500 )

SELECT
    Student.ID [StudentID],
    Assignment.ID [AssignmentID]
FROM 
    Student
    INNER JOIN StudentAssignment ON Student.ID = StudentAssignment.StudentID
    INNER JOIN Assignment ON Assignment.ID = StudentAssignment.AssignmentID

500 , . 60 (50 + 10), , .

+3

, SQL- OO , .

, OO , . SQL .

Student , ? , ? ?

, , , .

- StudentAssignment, Student Assignment?

, . Student Assignment.

() SQL , ?

, , , , .

+1

All Articles