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

uninjuredaccurate's avatar

hasManyThrough?

So,

I got a problem...

I got three tables (users, objects, objects_customer_managers)

+-------------------+
|      objects      |
+----+--------------+
| id |    address   |
+----+--------------+

+---------------------------+
| objects_customer_managers |
+----+----------------------+
| id | user_id |  object_id |
+----+----------------------+

+-------------------+
|       users       |
+----+--------------+
| id |     name     |
+----+--------------+

And basically, I want to do something like this in the Object Model:

#Object.php

public function customerManagers () {
    //
}

So that I can get all customer managers for that object like $object->customerManagers;

One objects.id has many rows in object_customer_managers.object_id. Every row also has object_customer_managers.user_id which belongs to users.id

Thanks in advance! I didn't really have luck with hasManyThrough :(

0 likes
1 reply
ctroms's avatar
ctroms
Best Answer
Level 15

Based on your database structure, it looks like you have the schema for a many to many relationship already setup.

On your object model, your customerManagers method should return the result of a call the belongsToMany method. Since the name of your pivot table deviates from what Eloquent expects, you can pass it as a second argument in the belongsToMany call.

public function customerManagers() 
{
    return $this->belongsToMany('App\Users', 'objects_customer_managers');
}

As outlined in the docs, you can add a similar method on your users model to perform the reverse.

Now you can get the objects customer managers by calling the customerManagers method defined on your object model.

$object->customerManagers()->get();

Please or to participate in this conversation.