Laravel 精简雄辩的结果->;带()急加载

Laravel 精简雄辩的结果->;带()急加载,laravel,eloquent,Laravel,Eloquent,我有一个我正在处理的查询,它被输入到一个javascript引擎中,其中返回了很多javascript中没有使用的信息。结果超过1MB,其中一些是由于一些急切的加载。以下是查询: $customers = Customer::where('customers.office_id', $officeid) ->where("customers.parent_id", null) ->with('lastAppointment') ->with('nextA

我有一个我正在处理的查询,它被输入到一个javascript引擎中,其中返回了很多javascript中没有使用的信息。结果超过1MB,其中一些是由于一些急切的加载。以下是查询:

$customers = Customer::where('customers.office_id', $officeid)
    ->where("customers.parent_id", null)
    ->with('lastAppointment')
    ->with('nextAppointment')
    ->select("customers.id","customers.family_id", "customers.gender", "customers.family_size", "family_value")
    ->get();
lastAppointment
的关系创建了一个返回的嵌套对象,其中包含
Appointment
表中的所有列,我实际上只需要一列
start\u at

如果执行
->leftJoin()
操作,我可以使用最终选择限制结果,如下所示:

->leftJoin(DB::raw("(select customer_id, MAX(start_at) as lastAppointment from appointments group by customer_id) as appt"), 'customers.id', '=', 'appt.customer_id')
->select("customers.id","customers.family_id", "customers.gender", "customers.family_size", "family_value", "appt.lastAppointment")

我只是想知道是否有一种方法可以使用
->with()

with函数将接受回调作为关系键的数组值。然后您就可以访问参考底图查询生成器实例,我想这就是您想要的:

->with(['lastAppointment' => function($query) {
    return $query->latest()->select('customer_id', 'start_at')
        ->groupBy('customer_id');
}])
您可以使用此代码

->with('lastAppointment:_relation_id,start_at')
其中,
\u relationship\u id
客户id
上次约会的主键
对应模型:
取决于您的表关系
。请参阅嵌套的即时加载的文档部分
p

->with('lastAppointment:\u relation\u id,start\u at')
\u relation\u id是父id或lastAppointment主键这是一个很好的解决方案!我尝试不使用
\u relationship\u id
,因为我实际上只需要原始值,但它不起作用。然而,当我按照你的方式去做时,我得到了比以前更清晰的回复。
“最后一次约会”:{“客户id”:195701,“开始时间”:“2018-07-17 11:00:00”}