【问题标题】:Lean Eloquent Results ->with() Eager Loading精益雄辩的结果 ->with() 渴望加载
【发布时间】:2018-07-25 19:01:40
【问题描述】:

我正在处理一个查询,该查询输入到 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() 做类似的事情?

【问题讨论】:

  • ->with('lastAppointment:_relation_id,start_at') _relation_id 是父 id 或 lastAppointment 主键
  • 这是一个很棒的解决方案!我尝试不使用_relation_id,因为我真的只需要原始值,但它不起作用。但是,当我按照你的方式进行操作时,我得到了比以前更干净的回复"last_appointment": { "customer_id": 195701, "start_at": "2018-07-17 11:00:00" }

标签: laravel eloquent


【解决方案1】:

您可以使用此代码

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

其中_relation_idcustomer_idlastAppointment 的主键对应模型:depends on your table relation。请参阅 Nested Eager Loading 的文档部分 https://laravel.com/docs/5.5/eloquent-relationships#eager-loadingp

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-09-18
      • 1970-01-01
      • 2020-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-05
      • 2018-06-01
      • 1970-01-01
      相关资源
      最近更新 更多