Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kvnkrft's avatar

Beginner Question re. Relationships (Team, TeamMember, User)

I have 3 tables: users, teams, and team_members. I want to show teams and the users in each team.

In my Team model I have:

public function teamMember()
{
    // A team member can be part of many teams
        return $this->hasMany(TeamMember::Class);
}

and in my TeamMember model I have:

public function user()
{
    // A team member can be part of many teams
        return $this->hasMany(User::Class);
}

Does that make sense? Or did I go completely wrong?

0 likes
6 replies
sherwinmdev's avatar
Level 6

assuming team_members table is something like... id user_id team_id

// User model

public function teamMembers()
{
    return $this->hasMany(TeamMember::class);
}

// Team model

public function teamMembers()
{
    return $this->hasMany(TeamMember::class);
}

// TeamMember model
public function team()
{
    return $this->belongsTo(Team::class);
}

public function user()
{
    return $this->belongsTo(User::class);
}
2 likes
kvnkrft's avatar

@w1n78 thank you for your help. In the TeamMember model, are we (in your code) creating a one-to-one relationship? Because a user can be in multiple teams (or that's the goal).

And, yes, you are correct. The team_members table has:

  • id
  • user_id
  • team_id
  • create_at
  • updated_at
sherwinmdev's avatar

@kvnkrft belongsTo() is an inverse of one to many https://laravel.com/docs/5.5/eloquent-relationships#one-to-many-inverse

a user can be in more than one team

a team can have more than one user

i'm running through your model in my head but something seems to be missing or can be handled differently. although it's late here and i had some beer earlier haha. hope i'm not steering you in the wrong direction. but generally that's how i handle pivoting

kvnkrft's avatar

Hi @w1n78 you're suggestions sure seems to work. I'm getting the results that I'm looking for - so I think you've done a great job. Maybe it's a magical make-you-better beer?!

1 like
sherwinmdev's avatar

@kvnkrft glad i could help :) i'd drink another but i'm pulling my hair out on a password issue that i hope someone in this forum can help.

Please or to participate in this conversation.