簡體   English   中英

優化 Laravel Eloquent 查詢結果

[英]Optimise Laravel Eloquent Query Result

我在laravel-5.7中有一個作業表,其中表中的 5000 條記錄也有一些通過HasMany() 或 HasOne() Relation來的關系記錄。 我嘗試了多種類型的Eloquent 查詢以獲得快速結果。 但是Postman結果時間變為 10200 毫秒到 10700 毫秒,但是當我直接將其顯示到 postman 時,我將其變為 500 毫秒到 1100 毫秒。 我想在綁定表格 Laravel 資源或普通數組后在大約 800 毫秒內得到它。

問題是,當我嘗試直接顯示 Eloquent 結果時,它大約需要 600 毫秒到 1000 毫秒。 但是當我綁定到一個數組並在 postman 中顯示時,它需要 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 來優化查詢 在這里找到優化 Laravel 查詢 這對我來說是個好答案嗎? 我不知道。 請幫我。

請檢查我的形象。 在此處輸入圖像描述

Eloquent 查詢結果在此處輸入圖像描述

首先,嘗試優化這個:

$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 條件下使用的字段添加索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM