使用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();