[英]I need help to turn some raw SQL into Eloquent code
正如標題所說,我無法將我的 SQL 代碼轉換為 Eloquent。
這是原始的 SQL:
select * from `students`
where (
select status_student.id from `status_student`
WHERE
status_student.id = (SELECT MAX(status_student.id) from `status_student`
WHERE
status_student.student_id = students.id)
AND
status_student.status_id = 6
)
IS NOT NULL;
這是到目前為止的代碼:
$status = $this->request->get('status');
if ($status !== "0") {
dd($query = Student::where(function($q) use($status){
$q->where('status_student.id', function($q2) use ($status) {
$q2->selectRaw('MAX(status_student.id)')
->where('status_student.student_id', '=', 'students.id')
->where('status_student.status_id', '=', $status);
});
})->toSql());
}
轉換為 SQL:
"select * from `students` where (`status_student`.`id` = (select MAX(status_student.id) where `status_student`.`student_id` = ? and `status_student`.`status_id` = ?))
所以它還不能正常工作。
我在介紹 IS NOT NULL 條款時遇到了麻煩
select status_student.id from 'status_student'
而不僅僅是
status_student.id =
我應該如何修改我的代碼以獲得所需的 SQL?
謝謝。
$status = request()->get('status');
if ($status !== "0") {
dd($query = Student::where(function($q) use($status){
$q->where([['status_student.id' => function($q2) use ($status) {
$q2->selectRaw('MAX(status_student.id)')
->where('status_student.student_id', '=', 'students.id')
->where('status_student.status_id', '=', $status);
}],
['status_student.id', '<>', null]
]);
})->toSql());
}
生成 SQL 查詢:
SELECT *
FROM `students`
WHERE (((`status_student`.`student_id` = ?
AND `status_student`.`status_id` IS NULL)
AND `status_student`.`id` IS NOT NULL))
不確定我是否理解正確,但我認為您只是語法不正確
試試這個:
$status = $this->request->get('status');
if ($status !== "0") {
// log the queries:
\DB::enableQueryLog();
$query = Student::with([
'statusStudent' => function($q1) use($status) {
$q1->where('status_student.id', function($q2) use ($status) {
$q2->selectRaw('MAX(status_student.id)')
->where('status_student.student_id', '=', 'students.id')
->where('status_student.status_id', '=', $status);
});
}
])
->get();
$pureQuery = \DB::getQueryLog();
dd($pureQuery);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.