user2067888
user2067888

Reputation: 1165

Laravel eloquent query to get the result groupBy(month)

How to get a result with groupBy(month('start_date'))

So far I have

    $this->data['earnings'] = DB::table('documents')
        ->leftJoin('users','users.id', '=', 'documents.users_id')
        ->leftJoin('users_editors','users_editors.user_id','=','users_id')
        ->groupBy(month ('start_date'), 'DESC')
        ->sum('amount')
        ->get();

I am trying to get earnings for all the editors groupBy month which will take month from start_date to have a groupBy on. Thanks

Upvotes: 0

Views: 1461

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81167

In order to use (My)SQL functions you need raw statements, that are not processed and bound by PDO or, in this case, treated as a field name:

->groupBy(DB::raw('month(start_date)'))

In order to make it work as you expect:

->selectRaw('month(start_date) as month, sum(amount) as sum')

->groupBy(DB::raw('month desc'))
// or:
->groupBy('month')
->orderBy('month', 'desc')

->get();

Upvotes: 1

Related Questions