1
votes

I have three tables as below:

 ------------------------------
| users  | projects  | clients |
|--------|-----------|-------- |
| id     | id        | id      |
| name   | client_id | name    |
|        | user_id   |         |
|        | name      |         |
 ------------------------------

So basically the relationship is like:

User hasMany Project
Project belongsTo Client

My question is:
How can I get all clients of a user using eloquent?

Seems like I cannot user hasManyThrough method as there are no project_id in clients table.

So what I wish to achieve is :

foreach($users as $user)
     foreach($user->clients as $client) //HOW TO SET UP THIS RELATION?
         foreach($client->projects($user)->get() as $project)
1
you must have a relation between user and project models in laravel - Jamal Abdul Nasir
I know I could get the user projects directly (User hasMany Project), but I wish to get them through the Client Model, which mean even a client is not belong to the user, as long as the client's project is belongs to the user, then the the user are able to get the Project through Client. - Park Lai
Did you try hasManyThrough relationship? - Jamal Abdul Nasir
@JamalAbdulNasir For now the relationship is like User hasMany Projects, Project belongsTo Client, I think hasManyThrough is only applicable on one to many relation, since there are no project_id in Client table. - Park Lai
and what is the realation of projects to users? - Jamal Abdul Nasir

1 Answers

0
votes
    $users = User::with('projects')->get();
    
    // organize cleints' project and add for each user  
    foreach ($users as $user) {
        // order projects by client_id
        $projects = Collect($user->projects->toArray());
        $clients = $projects->groupBy('client_id');

        // keep projects data in 'projects' index 
        $temp = array();
        foreach($clients as $client => $projects){
            $temp[$client] = array('projects' => $projects);
        }

        // add clinets data for each user
        $user['clients'] = $temp;
    }

    // output
    foreach($users as $user)
        foreach($user->clients as $client)
            foreach($client['projects'] as $project)
                echo 'user-'.$project['user_id'].', clinet-'.$project['client_id'].', project-'.$project['name'].'<br>';

Above code generated this output for me:

enter image description here