Level 58
Here's how you can write the above SQL query using Laravel's DB::table() facade:
DB::table('exam_application_fees AS ExamFees')
->join('students AS Student', 'ExamFees.student_id', '=', 'Student.id')
->whereNotIn('Student.student_id', function($query) {
$query->select('student_id')
->from('payments')
->where('exammonth_id', '=', 3);
})
->where('ExamFees.exammonth_id', '=', 3)
->where('Student.course_id', '=', 3)
->update([
'ExamFees.fine_amount' => 100,
'ExamFees.total_amount' => DB::raw('ExamFees.total_amount + 100')
]);
Explanation:
- We start by calling the
DB::table()method and passing in the name of the first table (exam_application_fees) as well as an alias (ExamFees). - We then join the
studentstable using thejoin()method and specify the join condition (ExamFees.student_id = Student.id). - Next, we use the
whereNotIn()method to exclude any students who have already made a payment for the given exam month (using a subquery). - We add two more conditions using the
where()method to filter by the exam month and course ID. - Finally, we call the
update()method and pass in an array of column-value pairs to update thefine_amountandtotal_amountcolumns. Note that we use theDB::raw()method to add a raw SQL expression for thetotal_amountcolumn, since we want to increment its value by 100.
I hope this helps! Let me know if you have any questions.