繁体   English   中英

在Laravel Raw Select语句中获取列总和

[英]Getting the sum of columns in a Laravel raw select statement

我试图获取在Laravel select语句中返回的记录的总和,但我似乎无法正确地做到这一点。

我的原始声明如下:

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

我试过在->select行的最后一个元素之后添加以下内容,但我不断收到错误;

DB::raw('sum(poll_votes.vote_count) total_votes')

任何帮助将不胜感激

要解决您收到的错误, groupBy->get方法之前使用groupBy

->groupBy('polls.id');

您希望对Colum求和或对所有记录进行计数: https : //laravel.com/docs/5.8/queries#aggregates

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM