Laravel两个模型之间的直接和间接关系


Laravel Direct and Indirect Relationship between same two models

这个问题扩展了Laravel文档中提供的示例Eloquent : Working Pivot Table。

我需要应用程序中的以下关系:

User belongsToMany Role
Role belongsToMany Task
User belongsToMany Task
User belongsToManyThrough Role->Task (Task through Role)
  • 因此,用户可以通过Role或直接与Task相关联。
  • 所有关系都是多对多的。

不清楚的部分是我需要如何在模型中设置这些,以便我可以使用诸如急切加载之类的东西来获得:

  • 通过角色与用户相关的所有任务
  • 与用户直接相关的所有任务
  • 与用户相关的所有任务

例如,为了启用所有这些关系,x 和 y 应该在下面是什么?

class User extends Eloquent {
    public function tasks()
    {
        return x;
    }
}
class Task extends Eloquent {
    public function users()
    {
        return y;
    }
}

我曾经遇到过属于ToManyThrough的问题,我使用以下代码解决了它:

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();
}

我知道它没有使用属于ToManyThrough的功能,它不是最优化的方式,但它正在工作。 :)