Kap*_*rma 7 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();
Run Code Online (Sandbox Code Playgroud)
is_download当表中没有相对条目时,只有一个问题为null.经过一些研究后,我发现有一个功能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();
Run Code Online (Sandbox Code Playgroud)
我能够在我的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
]));
});
Run Code Online (Sandbox Code Playgroud)
尝试这样:
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8373 次 |
| 最近记录: |