TIL: Laravel HasOneThrough model relationship
Context: Participants may earn race credits by volunteering at an event.
By using hasOneThrough()
we don't need to add the user.id column on the race_credits table. Simply using hasOneThrough relationship can access the user race credits through the volunteer model.
users
- id
- name
volunteers
- user.id
- event.id
race_credits
- volunteer.id
- event.id
// User.php
public function raceCredits()
{
return $this->hasOneThrough(
RaceCredit::class,
Volunteer::class
);
}