Enforcing single relationships between Laravel models

Viewed 37

I am designing an application for school portal and I have three models:

  • User
  • Teacher
  • Student

And maybe a pivot table "school_user".

  • Where User could be either Teacher or Student but not both.
  • Teachers and Students are added by school management first, then if a user registered he can assign himself to a Teacher or a Student account.

The problem is user_id is UNIQUE in both tables [Teachers & Student] so I can't use this field as a valid association.

I figured that I might use a pivot table may be school_user, But I can't find out how to do it.

Here are my tables:

User :

  • id
  • name

Teacher :

  • id
  • name

Student :

  • id
  • name

School_User:

  • user_id
  • model_id
  • model_type

How can I build relations that ensure that the user has only one association to either Teacher or Student?

0 Answers
Related