Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One to many relationship on the same table

Here is the situation:-

I have a table called Users. This contains user data for students and tutors as most of the data required is the same.

Having completed the system I am now told that the client would like to be able to assign students to tutors.

Is there a legitimate/ clean way I can create a one to many relationship within a single table, perhaps via a link table?

I've tried to think this through but whatever solution I come up with seems messy.

I would be grateful for any input.

Thanks

Phill

like image 990
Phill Avatar asked Aug 26 '14 08:08

Phill


People also ask

How do you represent a one-to-many relationship in a table?

In a one-to-many relationship, one record in a table can be associated with one or more records in another table. For example, each customer can have many sales orders. In this example the primary key field in the Customers table, Customer ID, is designed to contain unique values.

How do you handle a one-to-many relationship in a database?

To implement a one-to-many relationship in the Teachers and Courses table, break the tables into two and link them using a foreign key. We have developed a relationship between the Teachers and the Courses table using a foreign key.

How many tables can one-to-many relationship have?

one to many is two tables.

Which is the correct example for one-to-many relationship?

Example. If the two entity types are 'Customer' and 'Account,' each 'Customer' can have many 'Accounts,' but each 'Account' can only be owned by one 'Customer. ' In this case, we can say that each customer is linked to a number of accounts. As a result, the relationship is one-to-many.


1 Answers

Have you tried the following approach?

Make a new table, for example TutorStudent (choose a more appropriate name if needed). It should have two columns:

  • Tutor_ID
  • Student_ID

Both columns shall be the (composite) primary key, each column will be a foreign key to your Users table User_ID (I assume this is what you have).

So, if you have a tutor named Newton that has two students, Tesla and Edison, your Users table will have something like this:

  • User_ID, Name
  • 1, Newton
  • 2, Tesla
  • 3, Edison

and your TutorStudent table will have following values:

  • Tutor_ID, Student_ID
  • 1, 2
  • 1, 3

Relatively simple and doesn't require any modifications to your existing table.

Do take care when deleting users - use the delete cascade feature of your database system or do some maintenance work afterwards so your TutorStudent table doesn't go stale when updating/removing your users.

like image 190
darioo Avatar answered Sep 20 '22 13:09

darioo