rafaelmsantos
2 years ago

How to set a hasMany relation between 3 tables?

Posted 2 years ago by rafaelmsantos

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?

Please sign in or create an account to participate in this conversation.