skip to Main Content

Hello how do i sum table column for specific person (id). For example i have a table like this(this is table ProjectHistory table): enter image description here

and i want to display in my colabs view, all sum with specific collaborator so for example look image below.(this is Collaborators table)enter image description here

so if u look at image i have the id 2 for "David" collab. so i want to output in the column "Suma" the sum of ProjectHistory table for colab with id 2, so ( 3 + 500 = 503 ). and i want to do that for all collabs. for example for colab_id 3 i want to display in "Colaboratori" view(for id 3 means Valentin) 2500+1800 = 4300. How do i do that? give me an idea please

2

Answers


  1. You can use the sum in the QueryBuilder.

    Like so:

    $data = ProjectHistory::where('id', 1)->sum('suma');
    

    In your case, you may also use the withSum to obtain the result you want. Like so:

    $data = Collaborator::withSum('ProjectHistory', 'suma')->get();
    

    This resulting Collaborator will have an extra key now named: projecthistory_sum_suma which will have the sum of all the suma belonging to that Collaborator.

    This of course assumes that you have a hasMany relation with the ProjectHistory model.

    Login or Signup to reply.
  2. You can use the relational model:

    //In your Collaborator model
    
    public function projectHistory()
    {
       return $this->hasMany(ProjectHistory::class, 'foreign_key', 'local_key'));
    }
    
    //In your Collaborator controlller
    
    public function index()
    {
      $collaborators = Collaborator::with('projectHistory')->get();
      return view('your_view', compact('collaborators');
    }
    

    Then add projectHistory in your view.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search