精益雄辩的结果-> with()急切加载

时间:2018-07-25 19:01:40

标签: laravel eloquent

我正在处理一个查询,该查询会馈入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的关系创建了一个返回的嵌套对象,其中包含appointments表中的所有列,而我实际上只希望start_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()做类似的事情?

2 个答案:

答案 0 :(得分:1)

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

->with(['lastAppointment' => function($query) {
    return $query->latest()->select('customer_id', 'start_at')
        ->groupBy('customer_id');
}])

答案 1 :(得分:1)

您可以使用此代码

->with('lastAppointment:_relation_id,start_at')

其中_relation_idcustomer_idlastAppointment的主键对应模型:depends on your table relation。请参阅嵌套渴望加载的文档部分  https://laravel.com/docs/5.5/eloquent-relationships#eager-loading p