2
votes

This question extends the example Eloquent : Working With Pivot Tables provided in the Laravel Documentation.

I need the following relationships in an application:

User belongsToMany Role
Role belongsToMany Task
User belongsToMany Task
User belongsToManyThrough Role->Task (Task through Role)
  • So a user can relate to a Task either through a Role, or directly.
  • All relationships are many-to-many.

The part which is unclear to me is how I need to set these up in the models, so that I can use things such as eager loading to get:

  • All Tasks that relate to a user through roles
  • All Tasks that relate to a user directly
  • All Tasks that relate to a user

For instance, what should x and y be below in order to enable all of these relations?

class User extends Eloquent {

    public function tasks()
    {
        return x;
    }
}

class Task extends Eloquent {

    public function users()
    {
        return y;
    }
}
1

1 Answers

0
votes

I once had a problem with belongsToManyThrough and I solved it using this code:

public function Roles()
{
    $task_ids = DB::table('tasks_users')->where('user_id', $this->id)->lists('task_id');
    $role_ids = DB::table('tasks_roles')->whereIn('task_id', $task_ids )->lists('role_id');
    return Roles::whereIn('id', $role_ids)->get();
}

I know it's not using function belongsToManyThrough and it's not the most optimized way but it is working. :)