[英]Laravel with where eloquent builder. How to use db records values inside subquery?
我想在 laravel eloquent 子查询中使用记录字段
我试过这个
$clients = Client::with(['records' => function (Builder $query) {
// how can i take a record fields there?
$record = $query->first();
$query->where('time', Carbon::now()->subMinutes(10 + $record->duration);
}])->where('profile_id', $profile->id)->get();
如何才能做到这一点?
只需使用use()
$clients = Client::with(['records' => function (Builder $query) use ($record) {
$query->where('time', Carbon::now()->subMinutes(10 + $record->duration);
}])->where('profile_id', $profile->id)->get();
你的查询是错误的。 不可能在with
方法中使用$record
或$query->first()
。 您只能在最终的get()
之后使用这些数据。 由于 Eloquent 将首先获取与where
条件匹配的数据,除了“with”方法,然后它会生成一个查询以使用where in
获取预先加载的关系。
您可以使用原始查询来实现此查询,或者像其他答案一样,您必须先获取record
并在回调中使用它。
$clients = Client::with([
'records' => function ($query) {
$query->whereRaw("`time` = (10 + `duration`)");
}
])
->where('profile_id', $profile->id)
->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.