Search code examples
laravellaravel-5.3laravel-5.4

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?


Solution

  • 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();