Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vidhyaprakash85's avatar

DB::table() query doubt

Hi friends can you please guide how to write the sql query below in laravel DB::table() facade.

UPDATE
	exam_application_fees AS ExamFees,
	students AS Student
	SET ExamFees.fine_amount=100,
	ExamFees.total_amount = ExamFees.total_amount + 100
WHERE
	student_id NOT IN (
		SELECT
			student_id
		FROM
			payments
		WHERE
			exammonth_id = 3
	)
	AND ExamFees.exammonth_id = 3
	AND ExamFees.student_id = Student.id
	AND Student.course_id=3;
0 likes
3 replies
LaryAI's avatar
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 students table using the join() 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 the fine_amount and total_amount columns. Note that we use the DB::raw() method to add a raw SQL expression for the total_amount column, since we want to increment its value by 100.

I hope this helps! Let me know if you have any questions.

vidhyaprakash85's avatar

@LaryAI SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Student.student_id' in 'IN/ALL/ANY subquery' error

Pippo's avatar

it would be helpful to provide the structure of the tables. Anyway try to change whereNotIn like so:

 ->whereNotIn('ExamFees.student_id', function($query) {
	/* ... */
1 like

Please or to participate in this conversation.