[英]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.