我怎么总计每一行laravel

时间:2017-12-07 02:16:09

标签: php sql database laravel count

我想知道如何在该列'状态'中调用总数

在该列中,我有=“匹配”,“无应答”,“缺少意图”,“Webhook失败”,“低信心”取决于另一个功能

例如只计算“匹配”是可能的

但现在我要总计“匹配”+“无应答”+“缺少意图”+“Webhook失败”+“低信心”

我该怎么做?我尝试了以下方式,但它无法正常工作

foreach($sessionID as $key => $value)
{
  $countMatch = count(DiraChatLog::where('company_id', $companyID)->where('sessionID', $key)->where('status', 'Match')->get());
  $countNoAnswer = count(DiraChatLog::where('company_id', $companyID)->where('sessionID', $key)->where('status', 'No Answer')->get());
  $countMissingIntent = count(DiraChatLog::where('company_id', $companyID)->where('sessionID', $key)->where('status', 'Missing Intent')->get());
  $countWebhookFail = count(DiraChatLog::where('company_id', $companyID)->where('sessionID', $key)->where('status', 'Webhook Fail')->get());
  $countLowConfidence = count(DiraChatLog::where('company_id', $companyID)->where('sessionID', $key)->where('status', 'Low Confidence')->get());
  $totalQuestion = $countMatch + $countNoAnswer + $countMissingIntent + $countWebhookFail + $countLowConfidence;
  $data[$key] = [
                  'total' => $totalQuestion,
                  'match' => $countMatch,
                  'no answer' => $countNoAnswer,
                  'missing intent' => $countMissingIntent,
                  'webhook fail' => $countWebhookFail,
                  'low confidence' => $countLowConfidence,
                ];
}

$totalQuestion = $countMatch + $countNoAnswer + $countMissingIntent + $countWebhookFail + $countLowConfidence;

1 个答案:

答案 0 :(得分:0)

再次查看了您的问题后,我可以看到您正在使用foreach循环并在循环的每次迭代中运行多个查询。

如果您使用以下内容,应该能够在一个查询中获取所有数据。

$data = DiraChatLog::selectRaw("
        SUM(IF(status = 'Match', 1, 0)) AS match,
        SUM(IF(status = 'No Answer', 1, 0)) AS no_answer,
        SUM(IF(status = 'Missing Intent', 1, 0)) AS missing_intent,
        SUM(IF(status = 'Webhook Fail', 1, 0)) AS webhook_fail,
        SUM(IF(status = 'Low Confidence', 1, 0)) AS low_confidence,
        COUNT(*) AS total,
    ")
    ->whereIn('sessionID', array_keys($sessionID))
    ->groupBy('sessionID')
    ->get();