skip to Main Content

In a scenario where we have a many-to-many relationship, what would be the ideal thing to implement an endpoint where you can get the data registered specifically for user X? For example, a class having multiple teachers and a teacher having multiple classes.

I’m using typeorm to make the relations. But on the front end, I have a screen that I need to get all the classes.

That’s why I thought of putting the array of classes in the teachers table, because if I implement only the endpoint to get all the classes, I will actually get all the classes, instead of just the classes registered for the user. Or do relationships already solve this problem?

In addition to the specific classes for each teacher, I need to get some data that is in the class. Like name, number of students, etc.

2

Answers


  1. It’s quite simple, the best solution would be to put an array of classes in your teacher table. Then they could consume this endpoint to consume the class data.

    Login or Signup to reply.
  2. You need a intermediated table, witch will have the Id of the Teacher (Primary Key of the Teachers table) and the Id of the Class (Primary Key of the Class table).

    This way you can know witch or how many class the teacher (ID) have and the same for direction, how many teachers have the class (ID) by query to this table

    Example:
    Table Teacher:

    Id Name
    1 Mary

    Table Class

    Id Name
    1 Math
    2 Geo

    Table TeachersClass

    Id TeacherId ClassId
    1 1 1
    1 1 2

    To know the teacher Mary class:

    $ Select * From TeachersClass Where TeacherId = 1
    

    And at the end, with the Class Id you get all information you need from the class table.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search