gpt4 book ai didi

php - 在 Laravel 中使用 IFNULL

转载 作者:可可西里 更新时间:2023-11-01 06:37:07 25 4
gpt4 key购买 nike

我在 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 会变为 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();

我可以在我的 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
]));
});

最佳答案

像这样尝试:

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();

关于php - 在 Laravel 中使用 IFNULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36153019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com