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

Computanians's avatar

Many to many relationshhip with 3 tables

Hello everyone , i have 3 tables classes, subjects and teachers. i want to implements many to many relationship between the 3. i can do it with 2 tables but with 3 it's confused to me. please help!

0 likes
3 replies
SilenceBringer's avatar

@computanians there no many-to-many relationships for 3 tables out of the box.

You can make belongsToMany relationships between 2 tables and pass additional value of third column https://laravel.com/docs/8.x/eloquent-relationships#syncing-associations. This way you will not be able to use eager loading for all 3 tables

You can create separated model for pivot table (like ClassSubjectTeacher) and define all the relationships on this model. This way you can use eager loading for all relations

You can try to play with https://laravel.com/docs/8.x/eloquent-relationships#has-many-through

1 like
SilenceBringer's avatar

@computanians your pivot model belongsTo every of 3 related tables

public function teacher()
{
	return $this->belongsTo(Teacher::class);
}

Please or to participate in this conversation.