Search code examples
laraveleloquenteloquent-relationshiphas-one-through

Eloquent Relationships - hasOneThrough relation


Question
I want to get the matching schedule from it's table for an availability, using the shift_id in the availabilities table.
Availabilities is already a pivot table between users and shifts.

I thought a hasOneThrough relation is the way to go here, but i can't seem to get it to work.
What am I doing wrong?

Tables

Availabilities
- id
- user_id
- shift_id
- ...

Shifts
- id
- schedule_id
- ...

Schedules
- id
- ...

The Availability model

 public function schedule()
{
    return $this->hasOneThrough(
        'App\Schedule',
        'App\Shift',
        'schedule_id',
        'id',
        'shift_id',
        'id'
    );
}

Problem Somehow when I use PHP Artisan Tinker I get the schedule with id of Availability.id instead of the schedule with the id of shift.id. Since this schedule does not exist, i get an

$availability = App\Availability::find(1331);
$availability→schedule()→get();
Illuminate\Database\Eloquent\Collection {#3111
all: [],
}


Solution

  • After a lot of trying and inspecting the generated sql queries, I came to the conclusion that hasOneThrough can not be used in this way.

    I used a querybuilder instead:

       public function schedule()
     {
         return DB::table('schedules')
             ->join('shifts', 'shifts.schedule_id', '=', 'schedules.id')
             ->where('shifts.id', '=', "$this->shift_id")
             ->select('schedules.*', 'shifts.schedule_id')
             ->get();
     }