问题
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