In a Laravel 5.2 application I have three models: User
, Role
and Task
.
A User
is associated with multiple Roles
, and a Role
is associated with multiple Tasks
.
Therefore each user is associated to multiple tasks, through their roles.
I am trying to access all Tasks
associated with a User
, through their Roles.
The relevant parts of my models look like:
class User extends Authenticatable
{
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function tasks()
{
return $this->hasManyThrough('App\Task', 'App\Role');
}
}
class Role extends Model
{
public function tasks()
{
return $this->belongsToMany('App\Task');
}
public function users()
{
return $this->belongsToMany('App\User');
}
}
class Task extends Model
{
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
The following returns an SQL error;
Column not found: 1054 Unknown column 'roles.user_id'
It seems to be trying to access the relationship through a (non-existent) foreign key in the Role model, rather than through the pivot table.
$user = Auth::user;
$tasks = $user->tasks;
How can I access all tasks related to a user through these relationships?