Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

danny620's avatar

many through many relationship

Hi Guys

I've got 3 diffrent models booking, course, location

I want to be able to display the course name though the relationship

I have bookings that holds the location id the locations table holds the course id that then links to the course table which has the name how can I link the two together?

Do i need to use a has many through many on booking model? please see screenshoot http://viewingcloud.co.uk/eer-diagram.jpg

0 likes
5 replies
tykus's avatar

If you have a booking instance, then you can get the course name using:

$booking = Booking::with('location.course')->find($id); // eager loads the two relations (presuming you have relationships set up)
$booking->location->course->title;
danny620's avatar

I've tried return $this->hasManyThrough('App\Course', 'App\Location', 'course_id', 'id'); doestn return nothing

tykus's avatar

Based on the ERD you have given, this would be the wrong relationship type. You have a one-to-many between booking and location, and another between location and course

jekinney's avatar

Many to many uses a pivot table. As @tykus_ikus pointed out redo your relationships to reflect the correct relationships and your query should work.

Please or to participate in this conversation.