如何在 Laravel 中使用查询构建器来做到这一点? (子查询 WHERE NOT IN)
Posted
技术标签:
【中文标题】如何在 Laravel 中使用查询构建器来做到这一点? (子查询 WHERE NOT IN)【英文标题】:How do this in Laravel using the Query Builder? (Subquery WHERE NOT IN) 【发布时间】:2021-11-16 16:39:25 【问题描述】: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
);
此查询仅返回不在表中的任务:skipped_user_tasks、showed_user_tasks 和 current_user_tasks。另外,在选择时添加了“完成”字段:如果任务在完成的用户任务表中,则返回true,否则返回false。
【问题讨论】:
你可能正在寻找 whereNotIn 【参考方案1】:也许你可以试试这个,看看它是否有效,
$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();
【讨论】:
以上是关于如何在 Laravel 中使用查询构建器来做到这一点? (子查询 WHERE NOT IN)的主要内容,如果未能解决你的问题,请参考以下文章
Laravel 查询生成器 where 和 or where