在Laravel查询构建器中运行“exists”查询

时间:2017-07-28 13:08:15

标签: php mysql html5 laravel

我试图执行此操作:

SELECT * FROM `lms_test` 
WHERE NOT EXISTS 
   (SELECT * FROM `lms_studenttest` 
    WHERE `lms_test`.slug = `lms_studenttest`.testId 
    AND `lms_studenttest`.`studentId`='10a75c804b8851520993dedc42334c0f'
    ) 
AND `lms_test`.`testType`= 'Practice Test'

但没有获得成功 帮我做这个。

4 个答案:

答案 0 :(得分:0)

我想你可以尝试这个例子:

A::whereNotExists(function($query){
  $query->select(DB::raw(1))
        ->from('B')
        ->whereRaw('A.id = B.id');
  })
 ->get();

OR

DB::table('lms_test')
        ->whereNotExists(function ($query) {
            $query->select('lms_studenttest.*')
                  ->from('lms_studenttest')
                  ->where('lms_test.testType', 'Practice Test')
                  ->where('lms_studenttest.studentId', '10a75c804b8851520993dedc42334c0f')
                  ->whereRaw('lms_studenttest.testId = lms_test.slug');
        })
        ->get();

希望对你有所帮助!!!

答案 1 :(得分:0)

尝试:

DB::table('lms_test')
        ->whereNotExists(function ($query) {
            $query->select(DB::raw(1))
                  ->from('lms_studenttest')
                  ->where('lms_test.testType', 'Practice Test')
                  ->where('lms_studenttest.studentId', '10a75c804b8851520993dedc42334c0f')
                  ->whereRaw('lms_studenttest.testId = lms_test.slug');
        })
        ->where('testType','Practice Test')
        ->get();

答案 2 :(得分:0)

尝试这个(我不在实际数据上检查,我只写逻辑):

SELECT *
    FROM `lms_test` 
    LEFT OUTER JOIN `lms_studenttest`
        ON `lms_test`.slug = lms_studenttest`.testId 
        WHERE `lms_studenttest`.testId IS NULL
        AND `lms_studenttest`.`studentId`='10a75c804b8851520993dedc42334c0f'
        AND `lms_test`.`testType`= 'Practice Test'

答案 3 :(得分:-1)

尝试以下条件查询,并告诉我是否有帮助:

if (User::where('email', '=', Input::get('email'))->exists()) {
  // user found
}