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

homoky's avatar

Pivot table with 3 tables (subscriber, status, account)

Hi there,

I am stucked at this situation. I have 3 tables:

group – id – name

subscriber – id – name

status – id – name

And I need Eloquent relations to get this table:

account_status_subscriber

  • group_id
  • subscriber_id
  • status_id

But I dont know how to get this done with Eloquent Relations. I searched the web for some solutions but did not find someting usefull.

Thank you very much.

0 likes
4 replies
rcubitto's avatar
rcubitto
Best Answer
Level 11

There's no way of defining a 3-way relationship. You can relate just 2 models and the 3rd one as part of the pivot table.


// App/Group.php
public function subscribers() {
    return $this->belongsToMany(App\Subscriber::class)->withPivot('status_id');
}

public function statuses() {
    return $this->belongsToMany(App\Status::class)->withPivot('subscriber_id');
}


// App/Subscriber.php
public function groups() {
    return $this->belongsToMany(App\Group::class)->withPivot('status_id');
}

public function statuses() {
    return $this->belongsToMany(App\Status::class)->withPivot('group_id');
}

// App/Status.php
public function groups() {
    return $this->belongsToMany(App\Group::class)->withPivot('subscriber_id');
}

public function subscribers() {
    return $this->belongsToMany(App\Subscriber::class)->withPivot('group_id');
}

2 likes
homoky's avatar

Oh, I see, did not know that.

But how do I get subscriber in group with specific status? Thanks!

Group::find(1)->subscribers()->...

StefanVoinea's avatar

You should have this relationship

one group hasMany subscribers one subscriber belongsTo a group one subscriber hasOne status one status belongsToMany user

rcubitto's avatar

@homoky

If you want the subscribers of a group with a specific status

$subscribers = Group::find(1)->subscribers()->wherePivot('status_id', 2)->get();
4 likes

Please or to participate in this conversation.