在laravel中使用IFNULL

时间:2016-03-22 11:20:00

标签: php mysql sql database laravel

我在laravel中有一个查询工作正常。

$subjects = $app->db->table('subjects')->LeftJoin('downloads', 'subjects.subjectID', '=', 'downloads.subject_id')
        ->where('universityID', $currentUser->universityID)->where('semesterID', $currentUser->semesterID)->where('courseID', $currentUser->courseID)
        ->select('subjects.subjectID', 'subjects.subjectName', 'subjects.price',  'downloads.is_download' )
        ->orderBy('subjectID')
        ->get();

当表中没有相对条目时,is_download只有一个问题为空。经过一些研究后,我发现有一个函数IFNULL,我可以将is_download null更改为0。所以这是我的查询无法正常工作。空白屏幕正在显示。

$subjects = $app->db->table('subjects')->LeftJoin('downloads', 'subjects.subjectID', '=', 'downloads.subject_id')
        ->where('universityID', $currentUser->universityID)->where('semesterID', $currentUser->semesterID)->where('courseID', $currentUser->courseID)
        ->select('subjects.subjectID', 'subjects.subjectName', 'subjects.price',  IFNULL( `downloads`.`is_download` , 0 ) )
        ->orderBy('subjectID')
        ->get();

我可以在我的phpmyadmin中编写此查询,但不知道如何写入laravel

这是api,所以整个代码看起来像

use Illuminate\Database\Query\Expression as raw;
use project\Models\Subject;
use project\Models\Semester;
use project\Models\StudentRegistration;

$app->get('/api/getSubject/:studentID', function($studentID) use ($app) {
error_reporting(E_ALL);
    $currentUser = StudentRegistration::where('studentID', $studentID)->first();

$subjects = $app->db->table('subjects')->LeftJoin('downloads', 'subjects.subjectID', '=', 'downloads.subject_id')
        ->where('universityID', $currentUser->universityID)->where('semesterID', $currentUser->semesterID)->where('courseID', $currentUser->courseID)
        ->select('subjects.subjectID', 'subjects.subjectName', 'subjects.price',  IFNULL( `downloads`.`is_download` , 0 ) )
        ->orderBy('subjectID')
        ->get();
print_r($subjects);
    return $app->response->write(json_encode([
                'error' => 0,
                'subjects' => $subjects
    ]));
});

3 个答案:

答案 0 :(得分:5)

试试这样:

DerivedWithoutInterface

答案 1 :(得分:1)

您只需要这样使用

DB::raw('IFNULL( downloads.is_download, 0) as is_download')

答案 2 :(得分:0)

这是我的代码

->whereRaw('customer_id = IFNULL(?, customer_id)', [$request->customer_id])