laravel 中的控制器查询 foreach 循环出现问题

Trouble in Controller Query foreach loop in laravel

大家好,

任何人都可以帮助我使用此代码。

public function submitranking(Request $req){
    $dataCandidate = Candidate::all();

    foreach($dataCandidate as $Candidate){
        $judgeRate = Score::where('canId',$Candidate->id )
        ->where('catId',$req->catId )
        ->where('judgeId',$req->judgeId)
        ->sum('score');
        dd($judgeRate);
    }

}

我dd($judgeRate)只显示一条记录,应该显示考生的所有分数?我怎样才能让它循环并显示所有候选人的总分...请帮忙

您可以使用 pluck 函数获取所有候选人的 id 并使用 whereIn.

因此,无需使用循环,使用 group by 和简单的原始查询。

只需更改您的功能,例如,

public function submitranking(Request $req){

    $dataCandidate = Candidate::all()->pluck('canId');

    $judgeRate = Score::whereIn('canId',$dataCandidate)
                 ->where('catId',$req->catId )
                 ->where('judgeId',$req->judgeId)
                 ->select('catId',DB::raw('COUNT(score) as total_score'))
                 ->groupBy('catId')
                 ->get();
    dd($judgeRate);
}

您可以在此处查看文档:https://laravel.com/docs/5.5/queries#where-clauses

希望你明白。

你应该试试这个:

public function submitranking(Request $req){

    $dataCandidate = Candidate::get();

    foreach($dataCandidate as $Candidate){
        $judgeRate = Score::where('canId',$Candidate->id )
        ->where('catId',$req->catId )
        ->where('judgeId',$req->judgeId)
        ->sum('score');

        print('<pre style="color:red;">');
        print_r($judgeRate);
        print('</pre>');
    }
    exit;  
}

你应该试试这个:

public function submitranking(Request $req){

    $dataCandidate = Candidate::get();

    foreach($dataCandidate as $Candidate){
        $judgeRate = Score::select('score_id',DB::raw("SUM(score) as score"))
        ->where('canId',$Candidate->id )
        ->where('catId',$req->catId )
        ->where('judgeId',$req->judgeId)
        ->get();

        print('<pre style="color:red;">');
        print_r($judgeRate);
        print('</pre>');
    }
    exit;    
}