代码之家  ›  专栏  ›  技术社区  ›  mps

Laravel空间许可许多通过?查询

  •  0
  • mps  · 技术社区  · 1 年前

    我有两个表:时间表和任务,具有一对一的关系

    class Schedule extends Model
    {
        public function task() {
            return $this->belongsTo(Task::class, 'task_id');
        }
    

    任务模型与具有Task_role透视表的空间角色具有一对多关系:

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

    如何进行查询以检索与具有登录用户权限的任务相关联的所有计划?

    例如 任务:

    身份证件 名称
    1. 任务1
    2. 任务2
    3. 任务3

    任务角色(_R):

    task_id 角色id
    1. 1.
    2. 3.
    3. 1.

    日程

    身份证件 名称 task_id
    1. 时间表1 1.
    2. 时间表2 1.
    3. 时间表3 5.

    空间模型_空间(_R):

    角色id 型号_type 型号_id
    1. 应用程序\模型\用户 2.
    2. 应用程序\模型\用户 1.
    3. 应用程序\模型\用户 5.

    当用户2登录时,他应该只能看到时间表1和2。

    1 回复  |  直到 1 年前
        1
  •  1
  •   elemes    1 年前

    使用hasManyThrough是理想的,但这意味着要对您的模式进行一些修改。 但是,您可以通过链接Eloquent关系和自定义查询来实现此结果。 以你为例,你可以通过

    获取用户的所有角色ID,然后获取与这些角色相关联的所有任务,最后根据该ID确定时间表。

    或者,您可以在用户上定义一个自定义方法来执行同样的操作。

    带有代码的示例。

    
    // In your Schedule model
    
    public static function getSchedulesForUser($user)
    {
       // Get the role IDs of the user
        $roleIds = $user->roles()->pluck('id');
    
        // Get tasks associated with these roles using Eloquent relationship
        $tasks = Task::whereHas('roles', function ($query) use ($roleIds) {
            $query->whereIn('id', $roleIds);
        })->get();
    
        // Extract task IDs from the tasks collection
        $taskIds = $tasks->pluck('id');
    
        // Return the schedules associated with these tasks
        return self::whereIn('task_id', $taskIds)->get();
    }
    
    

    //in your User model 
    
    
      public function schedules()
        {
            // Get role IDs
            $roleIds = $this->roles()->pluck('roles.id');
    
            // Get task IDs associated with these roles
            $taskIds = Task::whereHas('roles', function ($query) use ($roleIds) {
                $query->whereIn('roles.id', $roleIds);
            })->pluck('tasks.id');
    
            // Return schedules associated with these tasks
            return Schedule::whereIn('task_id', $taskIds)->get();
        }
    
    

    //directly in your controller 
    
    // Get the logged-in user
    $user = Illuminate\Support\Facades\Auth::user();
    
    // Get the role IDs of the logged-in user
    $roleIds = $user->roles->pluck('id');
    
    // Get the task IDs associated with these roles
    $taskIds = DB::table('task_role')
        ->whereIn('role_id', $roleIds)
        ->pluck('task_id');
    
    // Get the schedules associated with these tasks
    $schedules = Schedule::whereIn('task_id', $taskIds)->get();