appointment
可以有許多狀態,但最後創建的appointment
和status
之間的關係是約會的當前狀態。在我的Appointment Datatable中,我想顯示相關代理,InstructionType
,SignUpCustomer
和最新的status
。我想paginate
這些記錄在10
每頁。如何優化此雄辯查詢以刪除相似的查詢
相關型號有:
Appointment
(belongsTo agent, instruction_type and sign_up_customer, belongsToMany status
)Agent
InstructionType
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 ()
請描述你的桌子是什麼樣的,你想要什麼以及你嘗試過什麼。 https://stackoverflow.com/help/how-to-ask – Indra
刪除$ query-> paginate(10)會將查詢語句減少到8.不過,我仍然在上面最後一行中有兩條語句^ – showFocus
如果你'重新尋找性能你必須使用RAW語句。雄辯不是爲了表現而設計的。 –