2016-03-22 26 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()'有什么错误? –