Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join and SUM in Laravel ELoquent

Database Structure is as follows:

Table: users

id | name | email | password

Table: analytics

id | user_id(fk) | article_id(fk) | revenue | date | clicks 

Now I want the list of all users with the sum of their own revenue from these two Tables.

What I tried is as follows:

$users = User::select('users*', 'analytics.*', 'SUM(analytics.revenue)')
         ->leftJoin('analytics', 'analytics.user_id', '=', 'users.id)
         ->where('analytics.date', Carbon::today()->toDateString())
         ->get();

But it is throwing me error.

like image 714
Siddharth Avatar asked Mar 11 '16 06:03

Siddharth


2 Answers

$users = User::select(\DB::raw('users.*, SUM(analytics.revenue) as revenue'))
         ->leftJoin('analytics', 'analytics.user_id', '=', 'users.id')
         ->groupBy('users.id')
         ->get();
like image 104
izupet Avatar answered Sep 22 '22 13:09

izupet


You may try this

$users = User::select('users*', 'analytics.*', DB::raw('SUM(analytics.revenue) As revenue'))
         ->leftJoin('analytics', 'analytics.user_id', '=', 'users.id')
         ->where('analytics.date', Carbon::today()->toDateString())
         ->get();
like image 35
Vipul Avatar answered Sep 19 '22 13:09

Vipul