2016-03-22 55 views
6

我在laravel中有一個查詢,它工作正常。在laravel中使用IFNULL

$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_downloadnull0。所以這裏是我的查詢不起作用。空白屏幕正在顯示。

$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

嘗試這樣的:

DB::Raw('IFNULL(`downloads`.`is_download` , 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', DB::Raw('IFNULL(`downloads`.`is_download` , 0)')) 
    ->orderBy('subjectID') 
    ->get(); 
+0

空白屏幕。不用找了。 –

+0

您是否使用\ DB :: table()而不是$ app-> db-> table()和\ DB :: Raw()?這應該很好。否則,當你在laravel中使用它時再次檢查你的查詢。 –

+0

使用'$ app-> db-> table()'有什麼錯誤? –