在UpdateOrCreate

时间:2018-10-30 19:36:38

标签: php laravel eloquent

我想将用户预测与比赛的实际得分进行比较。如果预测正确,那么我的预测表中的列result将更新为true。我正在使用集合来遍历我的比赛,并使用updateOrCreate来更新我的数据库字段。

如何正确添加if语句来检查值是否匹配?

代码

public function compareScores() {

    $matches = $this->getMatches();


    collect($matches['match'])
        ->each(function ($match, $key) {

            Prediction::updateOrCreate([
                'match_id' => $match['match_id'],
            ],[

                // if($match['homeScore'] == 'homeScore'  && $match['awayScore'] == 'awayScore') {
                //    'result' => true
                // }
            ]);

        });
}

public function getMatches() {

    $finished = Match::all()->where('status', 'FINISHED');

    return $finished;

}

1 个答案:

答案 0 :(得分:1)

我想我现在完全理解。在这种情况下,我不建议使用updateOrCreate。我会这样:

scored.thetas.1[i]

这将贯穿每个比赛并找到为此所做的所有预测。然后,它将检查预测homeScore和awayScore是否与匹配中的实际分数匹配。如果两个分数都匹配,它将结果更改为true。

请注意,如果您正确设置了模型关系,则可以进一步简化此操作。然后,您可以消除插入$ predictions = Prediction :: where('match_id,$ match-> id)-> get();的行。相反,您可以直接跳到foreach循环并运行以下代码:

public function compareScores() {

    $matches = $this->getMatches();


    foreach($matches as $match) {
        $predictions = Prediction::where('match_id',$match->id)->get();

        foreach($predictions as $prediction) {
            if($prediction->homeScore == $match->homeScore && $prediction->awayScore == $match->awayScore ) {
                $prediction->result=true;
                $prediction->save();
            }
        }
    }
}
相关问题