FYI: I went for the second option. More difficult but I think it is more future proof.
So I have three models/tables
- Gender (genders)
- Profile (profiles)
- ProfileGender (profile_genders)
Gender
- Holds all possible genders.
- Relates to "profile" with a "BelongsToMany" relationship.
public function profile()
{
return $this->BelongsToMany(Profile::class);
}
Profile
- Holds generic user profile information.
- Relates to "gender" with a "belongsToMany"
public function gender() {
return $this->belongsToMany(Gender::class, 'profile_genders')->withPivot('visibility');
}
ProfileGender
- "Pivot" table linking profiles with genders and holds the visibility status value
- Has no relationships in the model
Just one hickup here: This is a manyToMany relationship setup which means that it is possible for a profile to have more than one gender which is not ideal but can be prevented in the coding. It also makes the gender object return in an array.
Apparently, filtering and sorting a profile list on gender name is just a matter of leftJoining the profile_genders table and leftJoining the genders table on 'profile_genders.gender_id', '=', 'genders.id'.
This leaves me with a more defined question:
Is there a better way to organise the relationships? So a profile can have only one gender and the gender object returns as it's own object and not as an object in an array.