获取belongsToMany关联中的最后一条记录

时间:2017-03-30 22:49:11

标签: mysql laravel

我在约会和状态模型之间有一个belongsToMany关联。以下查询返回所有状态,我想更改它以拉出分配给约会的最后一个状态。

$query = Appointment::query();
            $query->with('statuses');
            $query->with("agent");
            $query->with("instruction_type");
            $query->with("sign_up_customer");
            $table = Datatables::of($query);

我尝试用此更改查询,但它无法正常工作。

$query->with('statuses')->latest();

这是我的原始查询:

select * from `users` where `users`.`id` = '1' limit 1
select count(*) as aggregate from (select '1' as `row_count` from `appointments`) count_row_table

select * from `appointments` limit 100 offset 0

select `statuses`.*, `appointment_status`.`appointment_id` as `pivot_appointment_id`, `appointment_status`.`status_id` as `pivot_status_id` 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

select * from `agents` where `agents`.`id` in ('1')

select * from `instruction_types` where `instruction_types`.`id` in ('1')

select * from `organisations` where `organisations`.`id` in ('1')

这样可行,但它会在状态

上运行两个查询
$query = Appointment::with(['statuses' => function ($query) {
                $query->latest()->first();
            }]);
            $query->with("agent");
            $query->with("instruction_type");
            $query->with("sign_up_customer");
            $table = Datatables::of($query);

2 个答案:

答案 0 :(得分:2)

为了从数据库中获取最新记录,您应该有一个created_at列来实现。在这种情况下,你可以这样做:

Appointment::with(['statuses' => function ($query) {
    $query->orderBy('created_at', 'desc')->first();
}])->get();

答案 1 :(得分:0)

尝试

$query->with(["statuses"=>function($q){
    $q->latest();
}])->get()

未经测试但猜测它应该有效