提问者:小点点

精简雄辩的结果->带()渴望加载


我有一个我正在处理的查询,它被输入到一个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(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")

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


共2个答案

匿名用户

您可以使用此代码

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

其中,\u relationship\u id客户id上次约会的主键对应模型:取决于您的表关系。请参阅嵌套的即时加载的文档部分https://laravel.com/docs/5.5/eloquent-relationships#eager-加载p

匿名用户

带有函数的将接受回调作为关系键的数组值。然后,您可以访问基础查询生成器实例,我认为这是您想要的:

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