【问题标题】:Laravel Direct and Indirect Relationship between same two modelsLaravel 相同两个模型之间的直接和间接关系
【发布时间】:2015-03-23 03:21:21
【问题描述】:

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

我在一个应用程序中需要以下关系:

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

【问题讨论】:

    标签: php laravel orm eloquent


    【解决方案1】:

    我曾经遇到过 belongsToManyThrough 的问题,我用这段代码解决了这个问题:

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

    我知道它没有使用函数 belongsToManyThrough 并且它不是最优化的方式,但它正在工作。 :)

    【讨论】:

      猜你喜欢
      • 2018-07-11
      • 1970-01-01
      • 2017-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      • 2017-06-10
      相关资源
      最近更新 更多