У appointment
может быть много статусов, но последним созданным отношением между appointment
и status
является текущий статус встречи. В моей таблице данных о встречах я хочу отобразить соответствующего агента, 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()