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

rafaelmsantos's avatar

How to set a hasMany relation between 3 tables?

How to set a hasMany relation between 3 tables? Imagine the example:

I have users, teams, roles and finally to connect all, user_teams. A user could belong to multiple teams, and have a different role in each team. My user_teams table is represented like this:

user_id integer
team_id integer
role_id integer

And this is my 3 models so far:

class User extends Eloquent
{
    public $timestamps = false;
    protected $table = 'users';
    protected $fillable = ['name', 'email', 'password', 'locale', 'token', 'status', 'created', 'updated'];

    public function teams()
    {
        return $this->belongsToMany('Models\Team', 'user_teams', 'user_id', 'team_id');
    }
}

class Team extends Eloquent
{
    public $timestamps = false;
    protected $table = 'teams';
    protected $fillable = ['name', 'slug', 'type', 'created', 'updated'];

    public function users()
    {
        return $this->belongsToMany('Models\User', 'user_teams', 'team_id', 'user_id');
    }
}

class Team extends Eloquent
{
    public $timestamps = false;
    protected $table = 'teams';
    protected $fillable = ['name', 'slug', 'type', 'created', 'updated'];

    public function users()
    {
        return $this->belongsToMany('Models\User', 'teams_users', 'team_id', 'user_id');
    }
}

Any ideas on how to achieve this?

0 likes
4 replies
giovanniciriello's avatar

It seems that the solution is make a custom method in your model, in which you define the complete relationship. What is an example of query you wish execute?

Please or to participate in this conversation.