从数据库中获取尚未存在关系的所有对象

时间:2015-12-13 16:16:06

标签: php mysql laravel laravel-5.1

我有以下查询,它正在做它的工作:

SELECT exams.id, exams.date FROM exams
WHERE exams.modul_id = (SELECT questions.modul_id FROM questions where questions.id = 5)
      AND NOT EXISTS (
          SELECT * FROM exam_question, questions
          WHERE questions.id = 5
              AND questions.id = exam_question.question_id
              AND exam_question.exam_id = exams.id
      )

它返回的所有考试都属于与考试相同的模型但尚未参加考试。

我想在Laravel中使用此查询,但我总是得到一个空结果(它不应该为空)

DB::table('exams')
->select(['id', 'date'])
->whereRaw('modul_id = '.$question->modul_id)
->whereNotExists(function ($query) use ($question) {
    $query->select(DB::raw(1))
        ->from('questions as q')
        ->join('exam_question as eq', 'q.id', '=', 'eq.question_id')
        ->join('exams as e', 'eq.exam_id', '=', 'e.id')
        ->whereRaw('q.id = '.$question->id);
})
->get();

laravel表达式的输出是:

select `id`, `date` from `exams` where modul_id = 1 and not exists (select 1 from `questions` as `q` inner join `exam_question` as `eq` on `q`.`id` = `eq`.`question_id` inner join `exams` as `e` on `eq`.`exam_id` = `e`.`id` where q.id = 5)

1 个答案:

答案 0 :(得分:0)

我在and not exists (...部分的SQL查询转储中看到问题,您选择以select 1 from开头,它将始终根据所选行数从您的表中选择数字1

select `id`, `date` from `exams` 
where modul_id = 1 
and not exists (
    select 1 from `questions` as `q` 
    inner join `exam_question` as `eq` on `q`.`id` = `eq`.`question_id`        
    inner join `exams` as `e` on `eq`.`exam_id` = `e`.`id` where q.id = 5)

您必须在查询构建器中使用$query->select(DB::raw(1)) ... - > $query->select('*') ...

DB::table('exams')
->select(['id', 'date'])
->whereRaw('modul_id = '.$question->modul_id)
->whereNotExists(function ($query) use ($question) {
    $query->select('*')
        ->from('questions as q')
        ->join('exam_question as eq', 'q.id', '=', 'eq.question_id')
        ->join('exams as e', 'eq.exam_id', '=', 'e.id')
        ->whereRaw('q.id = '.$question->id);
})
->get();

如果您用于创建查询的其余逻辑正确,则它将开始工作