laravel - 提高更新大表、Laravel 的性能

标签 laravel laravel-7

我有一个应该每周运行一次的函数(cron 作业),现在我尝试进行压力测试。

在我的请求中我得到:

Maximum execution time of 60 seconds exceeded

protected function updateAnswerHistory(){
    $answer_statistics = AnswerStatistic::select('question_id','paragraph_id','lkp_answer_id')->get(); //about 500row

    $history = AnswerHistory::select('id', 'question_id','paragraph_id','lkp_answer_id','correct_answer_score')->get(); //about 40k rows

    foreach ($history as $row) {

        if($row->question_id){
            $lkp_answer_id = $answer_statistics->where('question_id', $row->question_id)->pluck('lkp_answer_id')->first();
            if($row->lkp_answer_id === $lkp_answer_id){
                $row->update(['correct_answer_score' => 7]);
            }else{
                $row->update(['correct_answer_score' => 4]);
            }
        }

        if($row->paragraph_id){
            $lkp_answer_id = $answer_statistics->where('paragraph_id', $row->paragraph_id)->pluck('lkp_answer_id')->first();
            if($row->lkp_answer_id === $lkp_answer_id){
                $row->update(['correct_answer_score' => 7]);
            }else{
                $row->update(['correct_answer_score' => 4]);
            }
        }
    }
}

一件坏事是,从 foreach 进行查询需要时间,但我不确定如何改进这一点。

最佳答案

我不确定我是否正确理解您的数据库表结构,

但是从数据库获取数据并更新它们的成本很高

你应该以任何方式在数据库中进行更新过程......

这段代码的想法是根据question_id列连接两个表,然后进行“wheres”然后更新,我没有机会测试它......

AnswerHistory::join('answer_statistics','answer_statistics.question_id','answer_histories.question_id')-> where('answer_histories.question_id','!=',null)->
    where('answer_histories.lkp_answer_id','=',DB::raw('answer_statistics.lkp_answer_id'))
        ->update(['correct_answer_score' => 3]);

AnswerHistory::join('answer_statistics','answer_statistics.question_id','answer_histories.question_id')-> where('answer_histories.question_id','!=',null)->
    where('answer_histories.lkp_answer_id','!=',DB::raw('answer_statistics.lkp_answer_id'))
        ->update(['correct_answer_score' => 0]);

如果有帮助请告诉我

关于laravel - 提高更新大表、Laravel 的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62445576/

相关文章:

用于根据类型相互比较价格的Mysql查询

php - 拉维尔 5.7 : target is not instantiable while building

javascript - 如果数组循环内的项目不可用,则返回零并按工作日排列项目

laravel - Laravel 5.8 中的 Illuminate\Support\Fluent 中未找到方法 'references'

php - Laravel 7.x非法偏移类型

php - 无法将 Jetstream 包安装到 Laravel 项目

Laravel 7.1.x 丢失文件 : AuthenticatesUsers, RegistersUsers

php - Laravel 7 自定义身份验证不起作用

php - Laravel 7 : Redirect to different logins on different guards

laravel - 将 Laravel 7 升级到 8