0
I’m having a dilemma. I have tables that relate, like,:
internal_clients->Subsidiaries->departments->job_titles->users
I also have their respective models.
My question is:
How do I get all the data associated with users from the top of the chain (internal_clients) ?
I’m trying to follow the Laravel documentation using hasManyThrough.
But the doc only explains how to do it in a string of 3 tables. They teach to place an intermediate table (model) as the second parameter of the hasManyThrough(Classebase::class, Classeintermediaria:class).
However, in my case that has several tables between users and internal_clients, how would I do it ? What would be the intermediate table ?
I would like to make a query that returns which user internal_client, subsidiary, Department and jobTitle (associated with users).
I’m trying to do it this way:
Model Internalclient
public function users()
{
return $this->hasManyThrough(User::class, InternalClient::class);
}
Controller Usercontroller
public function allRelations($internalClientId)
{
$internalClient = InternalClient::find($internalClientId);
$users = $internalClient->users;
return response()->json($users, 201);
}
- The Internalclient id arrives in the controller above.
When I access to route, is returned to me the error below:
In short: I wonder if there is a way to get all the data (of all the tables that are in this hierarchical tree) that are associated with the User.
Thank you!
It’s hard to help you without first understanding the logic of relationships, because what you’re trying to do in your code is get all the
internal_clients
that relate tousers
. Generally speaking, given its relational structure, the best option is to usejoin
even– Erlon Charles
I am trying to make a logic something like this: https://paste.laravel.io/fa0089c6-7e18-415e-8f63-f86af867d324
– Gato de Schrödinger
$internalClients->departments->sections->jobTitles->users
implied that internalClients has a departments who has a sections who has a jobTitles which may have several users, would be the only way– Erlon Charles
If your reality doesn’t match the acid you’ll need to do Join even https://laravel.com/docs/7.x/queries#joins
– Erlon Charles
In fact it would be: "interbalClients" can have several "departments" which can have several "sections" which can have several "jobTitles" and which can have several "users". How did you put bold in the comment ? <b></b> ?
– Gato de Schrödinger
So your best alternative is to actually use Join
– Erlon Charles
And with ? I have been recommended to do with and it seems to me to get a cleaner code.
– Gato de Schrödinger