Laravel Query Builder with sum

16,814

i have found the answer, i thought it will would help some one else as well.

$games = \App\Models\Games::select(DB::raw('start,dayofweek,name,instructor_id,location_id,SUM(reservations) as reservations,SUM(reservationsmax) as reservationsmax,SUM(entries) as entries,SUM(entriesmax) as entriesmax,(SUM(entries) / SUM(reservationsmax)) * 100 as percentage'))
            ->where('club_id', $club_id)
            ->whereBetween('start', [$from, $to])
            ->where('hide_from_customers', 0)
            ->where('external_id', 0)
            ->orderBy('name')
            ->groupBy('start')
            ->groupBy('dayofweek')
            ->groupBy('name')
            ->get();
Share:
16,814
Muhabutti
Author by

Muhabutti

Updated on June 17, 2022

Comments

  • Muhabutti
    Muhabutti almost 2 years

    below is the query , and i am having this error

    SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax

            $games = DB::table('games')
            ->select('start','dayofweek','name','ins_id','location_id',
                DB::raw('SUM(reservations) as reservations'),
                DB::raw('SUM(reservationsmax) as reservationsmax'),
                DB::raw('SUM(entries) as entries'),
                DB::raw('SUM(entriesmax) as entriesmax'),
                DB::raw('(SUM(entries) / SUM(reservationsmax) * 100 as percentage'))
            ->where('club_id', $club_id)
            ->whereBetween('start', [$from, $to])
            ->where('hide_from_customers', 0)
            ->where('external_id', 0)
            ->orderBy('name')
            ->groupBy('start')
            ->groupBy('dayofweek')
            ->groupBy('name')
            ->get();