Eager load relation with parameters

Posted 1 year ago by MarioMacedo

In my Machine model I have the following relations

public function readings()
    return $this->hasMany(Reading::class)->orderByDesc('date');

public function nearestReadingFrom($date)
    $date = Carbon::createFromFormat('d-m-Y', $date)->format('Y-m-d');

    return $this->hasMany(Reading::class)
        ->where('date', '>=', $this->first_reading_date)
        ->orderBy(DB::raw('ABS(DATEDIFF(date, "' . $date . '"))'))

If I want to eager load the readings relation I can do the following and it works fine

Machine::select('location_id', 'id', 'code_id', 'first_reading_date', 'first_reading_in', 'first_reading_out', 'code_id')->with([
    'readings' => function ($query) {
        $query->select('machine_id', 'date', 'in', 'out');

However I don't know how to eager load the relation nearestReadingFrom($date) because of the parameter date.

Please sign in or create an account to participate in this conversation.