2017-03-31 31 views
0

appointment可以有許多狀態,但最後創建的appointmentstatus之間的關係是約會的當前狀態。在我的Appointment Datatable中,我想顯示相關代理,InstructionTypeSignUpCustomer和最新的status。我想paginate這些記錄在10每頁。如何優化此雄辯查詢以刪除相似的查詢

相關型號有:

  1. AppointmentbelongsTo agent, instruction_type and sign_up_customer, belongsToMany status
  2. Agent
  3. InstructionType
  4. SignUpCustomer

我有我的控制器,其產生的結果,此查詢我發送到Datatables。

$query = Appointment::with(['agent', 'instruction_type', 'sign_up_customer']); 
      $query->with(['statuses' => function ($query) { 
       $query->latest()->first(); 
      }]); 
      $table = Datatables::of($query); 

這是產生這兩個聲明,第一個罰款,我不需要最後一個。我如何優化查詢以刪除最後一條語句?

select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id`, `appointment_status`.`created_at` as `pivot_created_at`, `appointment_status`.`updated_at` as `pivot_updated_at` from `statuses` inner join `appointment_status` on `statuses`.`id` = `appointment_status`.`status_id` where `appointment_status`.`appointment_id` in ('2') order by `created_at` desc limit 1 

select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id`, `appointment_status`.`created_at` as `pivot_created_at`, `appointment_status`.`updated_at` as `pivot_updated_at`, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id`, `appointment_status`.`created_at` as `pivot_created_at`, `appointment_status`.`updated_at` as `pivot_updated_at` from `statuses` inner join `appointment_status` on `statuses`.`id` = `appointment_status`.`status_id` where `appointment_status`.`appointment_id` in ('2') order by `created_at` desc limit 1 

我也試過這樣:

型號:

/** 
    * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany 
    */ 
    public function statuses() 
    { 
     return $this->belongsToMany(Status::class, 'appointment_status')->withTimestamps(); 
    } 

    public function latestStatus() 
    { 
     return $this->statuses()->latest()->first(); 
    } 

控制器:

$query = Appointment::with(['agent', 'instruction_type', 'sign_up_customer', 'latestStatus']); 
      $table = Datatables::of($query); 

,但我得到這個錯誤:BadMethodCallException在Builder.php線2445: 調用未定義的方法Illuminate \ Database \ Query \ Builder :: addEagerConstraints ()

+0

請描述你的桌子是什麼樣的,你想要什麼以及你嘗試過什麼。 https://stackoverflow.com/help/how-to-ask – Indra

+0

刪除$ query-> paginate(10)會將查詢語句減少到8.不過,我仍然在上面最後一行中有兩條語句^ – showFocus

+0

如果你'重新尋找性能你必須使用RAW語句。雄辯不是爲了表現而設計的。 –

回答

0

你不能使用本地範圍做到這一點嗎? https://laravel.com/docs/5.4/eloquent#local-scopes

public function scopeLatest($query) 
{ 
    return $query->orderBy('created_at', 'DESC')->offset(0)->limit(1); 
} 

我沒有實際做過,但我不明白爲什麼它不會工作,(我也有不知道如何優化結果查詢是)。

+0

我認爲你的答案有點不相關。問題是關於如何優化SQL查詢。不是代碼表示 –

+0

感謝您的意見。 – Joe