Home > Enterprise >  Obtain the tasks of all projects related to a specific client
Obtain the tasks of all projects related to a specific client

Time:08-03

I have a customer table with a column that tells me the total number of projects for that customer; in the projects table I have a column with the total number of tasks related to that project.

Now what I need is to get the number of project tasks related to a particular customer because I have to add it in a new column in the customer table in order to report these tasks.

Can anyone kindly help me? Below is the code.

ClientController

public function index()
    {
        $clients = Client::withCount('projects')->get();              
        return view('client.index', compact('clients'));
    }

ProjectController

 public function index($id)
    {   

        $projects = Project::where('client_id', $id) ->withCount('tasks')->get();            
        return view('project.index', compact('projects'));
    }

CodePudding user response:

if i understand correctly and you want the sum of all task belonging to a client projects

   $tasks = Project::where('client_id', $id) ->sum('tasks');            

note this only returns a number (sum of tasks)

CodePudding user response:

If you want a count of the total tasks within all of a client's projects then you need an additional hasManyThrough relationship on your Client model;

    public function tasks ()
    {
        return $this->hasManyThrough('App\Project', 'App\Task');
    }

You can then count the tasks directly on the client model

    $clients = Client::withCount('projects')->withCount('tasks')->get();     
  • Related