在 Laravel ELoquent 中加入和求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35933954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:23:41  来源:igfitidea点击:

Join and SUM in Laravel ELoquent

mysqllaraveleloquent

提问by Siddharth

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 revenuefrom 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.

但它抛出了我的错误。

回答by izupet

$users = User::select(\DB::raw('users.*, SUM(analytics.revenue) as revenue'))
         ->leftJoin('analytics', 'analytics.user_id', '=', 'users.id')
         ->groupBy('users.id')
         ->get();

回答by Vipul

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

回答by Amirul

This maybe a bit late. Maybe will help someone else.

这可能有点晚了。也许会帮助别人。

You need to include every select columns in groupBy. In your case:

您需要在 groupBy 中包含每个选择列。在你的情况下:

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