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

crnkovic's avatar

Relationship inside a many-to-many

Hi folks!

I have many to many relationship for courses and students and the table is called course_student. However, in this pivot table, I have year_id that should have many to one relationship to another model. How should I structure this?

// Course model
public function students()
{
    return $this->belongsToMany(Student::class, 'course_student', 'course_id', 'user_id')
                     ->withPivot('')
                     ->withTimestamps();
 }

I'm not sure what should I put in withPivot function. Thanks in advance all!

0 likes
4 replies
leandromatos's avatar

If I understand your question, Your pivot table must contain an ID, and this ID will be the key to another model.

If this is not your question, explain the other better relationship so I can try to help you.

crnkovic's avatar

Yes, that is correct. Pivot table contains 2 keys that make a relationship (course_id, student_id) and another key (ID) that has a relationship (points to) to another model (ID) - ternary relationship.

d3xt3r's avatar

@jcrnkovic Relations work on models (in most general case) and pivot tables are just a way of holding this relationship information for a many to many relationship (along with extra pivot information) but saying that pivot's year_id has many to one relationship with another model makes it tricky, as pivot is not a model in itself.

May be if you can elaborate on how use plan to use it, there might be a better (possibly) solution.

Please or to participate in this conversation.