首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Laravel whereNotExists工作不正常

Laravel whereNotExists工作不正常
EN

Stack Overflow用户
提问于 2017-05-18 12:53:25
回答 1查看 517关注 0票数 1

据我所知,whereNotExists应该排除所传递的闭包中的所有查询。然而,我得到了意想不到的结果。

我想要做的是把所有申请关闭的学生都送回去;学生不是家长设定的缺课或缺席。我得到的是一群空荡荡的学生。

我做错了什么?

代码语言:javascript
运行
复制
    $students = DB::table('rounds')
                ->where('rounds.bus_id', '=', $bus_id)
                ->join('rounds_students', 'rounds_students.round_id', 'rounds.id')
                ->whereNotExists(function ($query) {
                     $query->select(DB::raw(1))
                        ->from('student_history')
                        ->where('student_history.student_id', '=', 'rounds_students.student_id')
                        ->where('student_history.activity_type', '=', 'absent')
                        ->orWhere('student_history.activity_type', '=', 'absent-by-parent');
                    })
                ->join('students', 'students.id', 'rounds_students.student_id')
                ->select('students.name')
                ->get();
            return $students;
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-18 14:38:47

  1. 您必须在whereRaw()where(DB::raw('...'))中使用原始表达式来定义NOT EXISTS子句中的关联条件。否则,'rounds_students.student_id'将作为字符串值传递,这不是您想要的。
  2. 注意ANDs和ORs在您的WHERE条件下!你的错。将其改为whereIn,使其更加简洁。

此外,您也不需要在select(DB::RAW(1))子句中真正使用EXISTS。数据库优化器知道,它们不需要将任何结果集返回到外部查询。这可能有助于保持您的代码不臃肿。

试一试

代码语言:javascript
运行
复制
$students = DB::table('rounds')
    ->select('students.name')
    ->join('rounds_students', 'rounds_students.round_id', 'rounds.id')
    ->join('students', 'students.id', 'rounds_students.student_id')
    ->where('rounds.bus_id', $bus_id)
    ->whereNotExists(function ($query) {
        $query->from('student_history')
            ->whereRaw('student_history.student_id = rounds_students.student_id')
            ->whereIn('student_history.activity_type', ['absent', 'absent-by-parent']);
    })
    ->get();
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44048340

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档