Trouble in Controller Query foreach loop in laravel

时间:2017-11-13 06:13:11

标签: php mysql laravel eloquent

Hello Again everyone,

can anyone help me with this code.

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);
    }

}

It is supposed to display all the scores of the candidates when I dd($judgeRate) it only display one record? How can I make it loop and display all the total sum scores of the candidates... Please help

2 个答案:

答案 0 :(得分:0)

You can use pluck function to get all ids of candidates and use whereIn.

So, there is no need to use loop, use group by and simple raw query.

Just change your function like,

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);
}

You can see docs here: https://laravel.com/docs/5.5/queries#where-clauses

Hope you understand.

答案 1 :(得分:0)

You should try this:

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;  
}

OR You should try this:

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;    
}