POV
POV

Reputation: 12005

How to use custom groupBy and LeftJoin in Laravel query?

I tried this query:

 $this->data = \DB::table('months')->select(DB::raw("months.id, COUNT(clients.id) as total"))
            ->leftJoin('clients','months.id','=','MONTH(created_at)')
            ->groupBy('months.id')
            ->first();

It returns me an error:

Column not found: 1054 Unknown column 'MONTH(created_at)' in 'on clause' 

How to fix it?

Upvotes: 0

Views: 1092

Answers (1)

brunohdaniel
brunohdaniel

Reputation: 622

Try to specify the table of your created_at column.

$this->data = \DB::table('months')->select(DB::raw("months.id, COUNT(clients.id) as total"))
            ->leftJoin('clients','months.id','=','MONTH(clients.created_at)')
            ->groupBy('months.id')
            ->first();

Upvotes: 1

Related Questions