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

oolongtea's avatar

3 table pivot example

I have 3 tables that need to join together with manyToMany relationship. I understand how to join 2 tables with a pivot table. For this case, I need to relate id from 3 tables in a pivot table.

Can you tell me how to setup the eloquent relationships? Is there any example?

Below is the example of the database setup.

Product

  • id
  • name

Attribute

  • id
  • name

Attribute_value

  • id
  • name

attribute_product_value_pivot

  • id
  • product_id
  • attribute_id
  • attribute_value_id
  • info-pivot
0 likes
3 replies
oolongtea's avatar

HI Dunsti, How does this pivot know where to look for

class DegreeStudent extends Pivot

for this

App\Student::find(1)->degrees()->find(1)->pivot->consultant()->get()

The only common thing is the pivot table degree_student. What else I need to do so that pivot->consultant() is referring to the class DegreeStudent?

thanks

Dunsti's avatar

The trick is, to declare the relations inside the Pivot-Class:

class DegreeStudent extends Pivot
{
    public function consultant()
    {
        return $this->belongsTo('App\Consultant');  // this is the relation to consultant
    }
}

Please or to participate in this conversation.