DEV Community

Cover image for HasMany Through Relationship with example and Diagram.
Code Of Accuracy
Code Of Accuracy

Posted on

HasMany Through Relationship with example and Diagram.

In Laravel, a has many through relationship allows you to define a relationship between three models. It's useful when you have a many-to-many relationship that is connected through an intermediate table.

For example, let's say you have three tables: users, roles, and permissions. Each user can have many roles, and each role can have many permissions. You can define a has many through relationship to allow a user to access all of their permissions through their roles.

Here's an example of how you might define the relationships in your models:

class User extends Model
{
    public function roles()
    {
        return $this->hasMany(Role::class);
    }

    public function permissions()
    {
        return $this->hasManyThrough(Permission::class, Role::class);
    }
}

class Role extends Model
{
    public function users()
    {
        return $this->belongsTo(User::class);
    }

    public function permissions()
    {
        return $this->hasMany(Permission::class);
    }
}

class Permission extends Model
{
    public function roles()
    {
        return $this->belongsTo(Role::class);
    }
}

Enter fullscreen mode Exit fullscreen mode

In this example, the User model has a hasManyThrough relationship with the Permission model through the Role model. This allows you to access a user's permissions by calling $user->permissions.

Here's a diagram of the relationship:

Image description

Oldest comments (0)