在 Laravel 中如何使用查询生成器执行此操作? (子查询 WHERE NOT IN)

How do this in Laravel using the Query Builder? (Subquery WHERE NOT IN)

SELECT DISTINCT
tasks.id,
tasks.category_id,
(CASE WHEN (SELECT task_id FROM completed_user_tasks WHERE user_id = 1 AND task_id = tasks.id) THEN true ELSE false END) AS completed
  FROM tasks
  WHERE tasks.id NOT IN
  (
    SELECT task_id FROM skipped_user_tasks WHERE user_id = 1
    UNION
    SELECT task_id FROM shown_user_tasks WHERE user_id = 1
    UNION
    SELECT task_id FROM current_user_tasks WHERE user_id = 1
  );

此查询仅 return 不在 table 中的任务:skipped_user_tasks、shown_user_tasks 和 current_user_tasks。另外,选择时增加了“已完成”字段:如果任务在completed_user_taskstable中,则return为true,否则为false。

]

也许你可以试试这个,看看它是否有效,

$check_events = DB::table('tasks')
              ->selectRaw('SELECT DISTINCT tasks.id, tasks.category_id, (CASE WHEN (SELECT task_id FROM completed_user_tasks WHERE user_id = 1 AND task_id = tasks.id) THEN true ELSE false END) AS completed')
              ->whereRaw('tasks.id NOT IN (SELECT task_id FROM skipped_user_tasks WHERE user_id = 1 UNION SELECT task_id FROM shown_user_tasks WHERE user_id = 1 UNIONSELECT task_id FROM current_user_tasks WHERE user_id = 1)')
              ->get();