优化Laravel雄辩的查询结果

时间:2020-06-05 14:56:21

标签: php laravel-5 eloquent query-optimization laravel-query-builder

我在 laravel-5.7 中有一个家庭作业表,其中表中的5000条记录还具有一些通过 HasMany()或HasOne()Relation 来的关系记录。我尝试了多种口才查询,以获得快速的结果。但是 Postman 的结果时间变为10200ms到10700ms,但是当我直接将其分配给Postman时,我将其变为500ms到1100ms。我想在绑定表单Laravel Resource或Normal Array后,在800毫秒左右获得它。

问题是,当我尝试直接显示Eloquent结果时,它大约在600ms至1000ms之间。但是当我绑定到一个数组并显示在邮递员中时,为什么要花费6200毫秒?我不知道吗?

    $page = $req->page ?$req->page:1;  // set starting value for look query limit.
    $user = Auth::user()->student()->first();
    $studentProfile = Auth::user()->student()->first();

    // collecting all homework id that have assigned to student.
    $studentHWList =  StudentHomeWork::where("student_id",$studentProfile->id)
        ->select('home_work_id')
        ->get()->pluck('home_work_id');

   // collecting page by page of homework id.
    $hwLimitList =  Homework::where('session_code', dnc($req->require('sid')))
            ->whereIn('id',$studentHWList )
            ->where('approved', '1')
            ->select('id')
            ->orderBy('updated_at','desc')
            ->get();
    $hwIndexes = $hwLimitList->pluck('id')->forPage($page,$this->recordLimit);

    $paginated = Homework::whereIn('id', $hwIndexes)
                        ->with( "user:id,username,name",
                                'subject:id,subject_name,subject_code',
                                'approveByUser','publishBy')
                        ->with(["likes"=>function($erw){
                                 $erw->select('id','home_work_id','complete_status','likes')
                                ->where("student_id", $studentProfile->id);
                        }])
                        ->with(['comment'=>function($qur){
                            $qur->where('parent_id',0)
                                ->where('user_id',$user->id);
                        }])
                        ->orderBy('id','desc')
                        ->get( );

    if( count($paginated))
    {
        $paginationData =  customPagination('getAllHW',$hwLimitList , $page , $this->recordLimit , $user, $studentProfile  );
        return response()->json(["error"=>0,"errmsg"=>"","paginationData"=>$paginationData  ,
            "response"=>['homework_list'=>$this->customResourceHWBinding($paginated , $req )],'auth'=>userType()]);

  

private function customResourceHWBinding($queryData , $request, $user, $studentProfile )
{
    $document_list =[]; $is_seen=0; $resultData =[];
  foreach ( $queryData as  $query )
  {
      if( count($query->document)  )
      {
          foreach($query->document as $document){
              if( $document->changed_filename )
              {
                  $file=""; $fileName ="";
                  $path =env('AWS_URL')."/uploads/".dnc($request->header('dbauth'))."/".$query->session_code."/homeWorks/";
                  if(is_s3FileExist( $path.$document->changed_filename ) )
                  {
                      $fileName =$document->changed_filename;
                 
                  }
                  $document_list[] = [
                      'oname'=> $document->changed_filename,
                      'ext'=>$fileName?explode('.', $document->changed_filename):"",
                      'url'=>$file,
                      'file_url'=>$document->changed_filename?$path.$document->changed_filename:""
                  ];
              }
          }
      }

      $resultData[] =   [
      'id'=>enc($query->id),
      'ids'=>$query->id,
      'pin_user_id'=>"",
      'pin_enabled'=>0,

      'created_by'=>$query->user->name,
      'created_by_image'=>getUserImage($query->user,$query->user->privilege,$request),
      'assignment_date'=>getDateFormat($query->assignment_date,0),
      'assigment_date_edit'=>"",
      'submission_date'=>getDateFormat($query->submission_date,1),
      'submission_date_edit'=>"",
      'class_code'=>$query->class_code,
      'subject'=>$query->subject?$query->subject->subject_name:"",   
      'topic'=>$query->topic,
      'is_student_seen'=> $this->studentHWSeen($query, $user, $studentProfile),
      'updated_at'=> date('d-m-Y H:i:s' , strtotime($query->updated_at)),
      'approved'=>$query->approved,
      'approve_by'=> '',
      'can_approve'=>0,
      'comment_count'=>0,
      'total_like'=>0,
      'documents_count'=>count($document_list)?count($document_list):0,
      'is_draft'=> $query->draft?$query->draft:0,
  ];
  }
  return $resultData;
}

private function studentHWSeen( $query , $user, $studentProfile)
{
    if(count($query->studentSeen))
    {
        foreach($query->studentSeen as $seen){
            if( user->privilege == 1  )
            {
                if($seen->student_id == $studentProfile->id )
                   return 1;
            }
        }
    }
    return 0;

}

我尝试使用资源,但这也需要3秒钟以上的时间。我尝试了许多其他人优化解决方案的方法,但在我的情况下不起作用。有人告诉使用查询生成器而不是Eloquent优化查询。在这里Optimising Laravel query中找到。对我来说是一个好答案吗?我不确定。请帮助我。

请检查我的图像。enter image description here

口才查询结果 enter image description here

1 个答案:

答案 0 :(得分:0)

首先,尝试对此进行优化:

$paginated = Homework::whereIn('id', $hwIndexes)
                        ->with( "user:id,username,name",'subject:id,subject_name,subject_code',
                            'approveByUser','publishBy')
                        ->with(["likes"=>function($erw){
                            $erw->select('id','home_work_id','complete_status','likes')
                                ->where("student_id",Auth::user()->student()->first()->id);
                        }])
                        ->with(['comment'=>function($qur){
                            $qur->where('parent_id',0)
                                ->where('user_id',Auth::id());
                        }])
                        ->orderBy('id','desc')
                        ->get( );

您在嵌套查询中运行相同的代码:Auth::user()->student()->first()->id

优化版本:

$studentId = Auth::user()->student()->first()->id;


$paginated = Homework::whereIn('id', $hwIndexes)
                        ->with("user:id,username,name", 'subject:id,subject_name,subject_code', 'approveByUser', 'publishBy')
                        ->with(["likes"=>function($erw) use ($studentId) {
                            $erw->select('id','home_work_id','complete_status','likes')
                                ->where("student_id", $studentId);
                        }])
                        ->with(['comment'=>function($qur) {
                            $qur->where('parent_id',0)
                                ->where('user_id',Auth::id());
                        }])
                        ->orderBy('id', 'desc')
                        ->get();

请记住将索引添加到您在where条件中使用的字段。