skip to Main Content

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


  1. 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();
    
    Login or Signup to reply.
  2. 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();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search