php - Getting the sum of columns in a Laravel raw select statement
I am trying to get the sum of the records that are returned in a Laravel select statement but I can't seem to get it right.
My original statement is as follows;
$results = DB::table('polls')->select('polls.id as poll_id', 'poll_votes.vote_count as vote_count', 'poll_options.id as poll_option_id')
->join('poll_options','polls.id','=','poll_options.poll_id')
->join('poll_votes', 'poll_options.id', '=', 'poll_votes.poll_option_id')
->where([['polls.status','=','1'], ['poll_options.status','=','1'],])
->get();
I have tried adding the following after the last element on the->select
line but I keep getting errors;
DB::raw('sum(poll_votes.vote_count) total_votes')
Any help would be greatly appreciated
Answer
Solution:
To fix the error you are receiving, use the
groupBy
before your->get
method:Answer
Solution:
You want the sum of Colum or Count all the records: https://laravel.com/docs/5.8/queries#aggregates