I want to use a record fields in laravel eloquent subquery
I tried this
$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();
How can this be done?
CodePudding user response:
Just use the 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();
CodePudding user response:
Your query is wrong. It is not possible to use the $record
or $query->first()
inside the with
method. You will only be able to use those data only after the final get()
. Since Eloquent will first fetch the data matching the where
conditions except the "with" method, and then it will generate a query to fetch the eager-loaded relationships using where in
.
You can achieve this query using a raw query, or like the other answer you have to fetch the record
first and use that in the callback.
$clients = Client::with([
'records' => function ($query) {
$query->whereRaw("`time` = (10 `duration`)");
}
])
->where('profile_id', $profile->id)
->get();