php - Getting the sum of columns in a Laravel raw select statement

621

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

931

Answer

Solution:

To fix the error you are receiving, use thegroupBy before your->get method:

->groupBy('polls.id');
760

Answer

Solution:

You want the sum of Colum or Count all the records: https://laravel.com/docs/5.8/queries#aggregates

People are also looking for solutions to the problem: javascript - How to make a modal popup button for all the images I have uploaded?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.