Search code examples
phpsqllaravellaravel-query-builder

How to convert raw SQL query to Laravel Query Builder


I need a following code to convert to Laravel query can any one help me with these.

SELECT id, `leave_name`, `total_leave_days`, leave_id, leave_taken_days FROM `leaves` AS t1 INNER JOIN ( SELECT leave_id, SUM(`leave_taken_days`) AS leave_taken_days FROM `leave_applications` WHERE user_id = 2 AND statuses_id = 2 GROUP BY leave_id ) AS t2 ON t1.id = t2.leave_id

I even tried but the output is not showing atall.

$user_leaves = DB::table('leaves')
        ->select('id', 'leave_name', 'total_leave_days', 'leave_id', 'leave_taken_days')
        ->join('leave_application', 'leave_application.leave_id', '=', 'leave.id')
        ->select('leave_application.leave_id', DB::raw("SUM(leave_taken_days) as leave_application.leave_taken_days"))
        ->where('user_id','=', 2)
        ->where('statuses_id','=', 2)
        ->get();

How can I solve this issue?

UPDATE

Relations between two models.

Leave Model

public function leave_application()
    {
        return $this->belongsTo(LeaveApplication::class, 'id' , 'leave_id');
    }

Leave Application Model

 public function leave()
    {
        return $this->belongsTo(Leave::class, 'leave_id', 'id');
    }

Solution

  • Actually I found my answer,

    $user_leaves = DB::table('leaves as t1')
                ->select('t1.id', 't1.leave_name', 't1.total_leave_days', 't2.leave_id', 't2.leave_taken_days')
                ->join(DB::raw('(SELECT leave_id, SUM(leave_taken_days) AS leave_taken_days FROM leave_applications WHERE user_id = ' . $user_id . ' AND statuses_id = 2 GROUP BY leave_id) AS t2'), function ($join) {
                    $join->on('t1.id', '=', 't2.leave_id');
                })
                ->get();