Sum of rows and groupby using eloquent

笑着哭i 提交于 2021-01-28 22:28:32

问题


Having the following columns:

category, rating, num_users, date_voted /*number of users*/

How do I get the rating grouped by category as the sum of the number of users over a given range of dates using eloquent

Category::groupBy('num_users') //returns the categories

Example of the Main table data

--------------------------------
category| rating| num_users| date_voted
---------------------------------------
Action  |5      |2         | 12-12-2015
Comedy  |2      |2         | 12-12-2015
Fantasy |3      |2         | 12-12-2015
Action  |4      |2         | 14-12-2015
Comedy  |5      |2         | 14-12-2015

I want the html table to be in the form of category vs ratings(between 1 and 5) eg

-----------------------------------------------------
Category|Rating 1|Rating 2|Rating 3|Rating 4|Rating 5|
------------------------------------------------------
Action  |2       |3       |5       |5       |9       |  
Comedy  |9       |8       |6       |9       |14      | 
Fantasy |1       |2       |3       |6       |7       | 

回答1:


if you want get sum of num users group by category you can use:

Category::groupBy('category')
->selectRaw('sum(num_users) as num_users , category')
->get();



回答2:


May be it will help you

Category::select(DB::raw('sum(users) as total_users'),'category')->groupBy('category')->get();


来源:https://stackoverflow.com/questions/35409620/sum-of-rows-and-groupby-using-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!