3-way relationship with Laravel and Eloquent

I already posted this on the laravel forums, but no one could help. Thought I'd post a second opinion here.

I need a little tutorial / help on how to structure my models. This is what i am trying to do

A user can be a member of several teams, but a user can play a different role in each team.

The idea is that the user sees a different set of data / functions depending on the role they occupy in the team.

So, I thought of something like:

Users
id, name, email, etc...

Teams
id, name, description

Roles
id, name

Team Users
user_id, team_id, role_id

The table team_memberswill tie 3 parts together. Defining user groups and their roles.

My questions:

  • This is the best way to go on such a relationship.
  • How to assign a user to a team with a role?
  • Using Eloquent, how do I get the user role in this command?
+4
1

, , , TeamMember , - :

//assign or update user team or role
$new_member = TeamMember::firstorCreate(array(
              'user_id' => $this->user->id,
              'team_id' => $team_id,
              'role_id' => $role_id,
              ));

//accessing the role of a user on a team
$role = TeamMember::where('user_id', '=', $user_id)
        ->where('team_id', '=', $team_id)->first()->role_id;

//get the name of the role
$role_name = Role::find($role)->name;
+2

All Articles