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?
2
Answers
Just use the
use()
Your query is wrong. It is not possible to use the
$record
or$query->first()
inside thewith
method. You will only be able to use those data only after the finalget()
. Since Eloquent will first fetch the data matching thewhere
conditions except the "with" method, and then it will generate a query to fetch the eager-loaded relationships usingwhere 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.