优化Laravel Eloquent查询结果.

问题描述 投票:0回答:1

我有一个作业桌在 laravel-5.7 表中的5000条记录中也有一些Relational记录,这些记录是通过 HasMany()或HasOne()关系。. 我试过很多类型的 口才查询 以获得快速的结果。邮递员 结果时间变成了10200ms到10700ms, 但是当我把这个结果直接显示在postman中时, 我把这个结果变成了500ms到1100ms.我想在绑定Laravel资源或普通数组后, 把它变成800ms左右.

问题是, 当我试图直接显示Eloquent结果时, 它需要600ms到1000ms.

    $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+secconds.我尝试了太多其他人优化的解决方案,但不工作在我的情况下。使用查询生成器而不是Eloquent来优化查询。.在这里找到 优化Laravel查询 ......这对我来说是一个好的答案吗? 我不确定,请帮助我。

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

雄辩的查询结果enter image description here

mysql laravel eloquent query-optimization laravel-5.7
1个回答
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条件下使用的字段中添加索引。

© www.soinside.com 2019 - 2024. All rights reserved.