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

JorgeFerrari's avatar

How to use accessory tables? HasManyTrough?

I have 3 tables

users

id
name

groups

id
name

users_groups

user_id
group_id

How do i create the relation in my Eloquent model to get all the groups from the current user? I'm having quite trouble understanding it.

0 likes
2 replies
JorgeFerrari's avatar

Found a explanation

class Current extends Model
{
    public function final()
    {
        return $this->hasManyThrough(
            'App\Final',
            'App\Intermediate',
            'intermediate_id', // Foreign key on Intermediate
            'final_id', // Foreign key on Final
            'id', // Local key on Current
            'id' // Local key on Intermediate
        );
    }
}

is this accurate?

Cronix's avatar

No, you'd just use a belongsToMany() relationship, and fix your lookup table name.

The lookup table name should be the combination of your 2 tables, singular, and in alphabetical order.

So, it should be group_user.

https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

Edit: hasManyThrough is for when you're wanting to go through multiple tables without having to get each one in between.

Think of it like you had these related tables

-Country
-State
-County
-City

And you wanted to get the cities in the country, without having to retrieve the state or county first.

You have a direct relationship, so should just need belongsToMany.

In Users.php

function groups()
{
    return $this->belongsToMany(Group::class);
}
$user = User::with('groups')->get();
// or

$user->groups; // if user is already loaded.
1 like

Please or to participate in this conversation.