May 20, 2018
7
Level 7
Laravel Eloquent triple table relation
Having three tables:
- Teams
- Users
- Badges
A User can belong to many Teams, and Badges can be assigned for every User-Team.
Options i thought until now:
- Create table "badges" with team_id and user_id as foreign.
- Create pivot table "badge_team_user" and assign the 3 foreigns.
And which would be the best way to query the results?
- $user->badges(team_id)
- $team->badges(user_id)
- $badges->printBadges(team_id, user_id)
Am i missing somethin better? Thanks!
Level 20
Ok. From my perspective, don't try to link all of that at once.
- User have many team, set this relations (Many to Many with
user_teamtable) - User have many badges, set this one (Many to Many with
badge_usertable) - Team have many badges, set this one (Many to Many with
badge_teamtable, or "One to Many" if a badge is always specific to a team).
I don't think you will able to use " Has Many Through" due to the many to many relations, but you should be able to retrieve data with nested eager loading.
//Retrieve user badges:
$user = User::with('badges')->find($userid);
//Retrieve user badges related to each team
$user = User::with('teams.badges')->find($userid);
//Retrieve all users of a team
$team = Team::with('users')->find($teamid);
//Retrieve all users of a team with badges
$team = Team::with('users.badges')->find($teamid);
//display achievable badges in a team
$team = Team::with('badges')->find($teamid);
//display all badges achieved by the user in a team - hard one
$user = User::with(['teams.badges' function ($q) {
$q->where('teams.id', $teamid);}])
->find($userid); //not sure it will work
//Retrieve all your data
$users = User::with('teams.badges')->get();
$teams = Team::with('users.badges')->get();
badges = Badge::with('teams.users')->get();
And you can add more constraint if needed : https://laravel.com/docs/5.6/eloquent-relationships#constraining-eager-loads
1 like
Please or to participate in this conversation.