I have a user that can belong to ONE of multiple different account types, I'm not sure the optimal way of setting up this relationship.
Say we have a User, that can be of account type Teacher, or Student, the base user object will contain all the shared attributes, while the teacher and student object will have the extended specific attributes for that type.
The way I see it as a kind of a mix between a pivot table and polymorphic relationship - as a User is either a teacher, or student, I can't use direct belongsTo(Student::class) or belongsTo(Teacher::class) relationship.
So if I use a pivot table called user_accounts that contains user_id, account_id, account_type, I'm unsure how to create the relationship correctly.
I expect the table to for example look like this
user_id | account_id | account_type
1 3 student
2 4 teacher
Normally in the user model to represent a relationship you would use
public function student()
{
return $this->belongsTo(Student::class);
}
The question is not knowing the account_type string, do we just do both $this->belongsTo(Student::class) and $this->belongsTo(Teacher::class) and let laravel deal with ignoring the invalid one, but I was wondering if it can be done dynamically, something like
public function userType()
{
return $this->belongsToMany($accountType::class); // doesn't work
}
But I don't think this is possible ?
Also, to set up the pivot relationship, I would normally do
$this->userType()->attach($teacher/$student);
But this doesn't seem to work either.
All the above obviously has to factor in the creation of the user object, the student/teacher object and the linkage between all.
Please any pointers would help, this is the tricky part as obviously making it right up front means retrieval and querying down the track is much better/efficient.