search

Home  >  Q&A  >  body text

How to sum elements of a specific person (id) - laravel

<p>Hi, how can I sum the table column for a specific person(id). For example, I have a table like this (this is the table ProjectHistory table): </p> <p>I want to display all sums for a specific collaborator in my colabs view, for example see the image below. (This is the collaborators table)</p> <p>So, if you look at the picture, I see the id 2 of the "David" collaboration. So I want to output the sum of the ProjectHistory table of colab with ID 2 in the "Suma" column, so ( 3 500 = 503 ). I want to do this for all collaborations. For example, for colab_id 3, I want to display (for id 3 means Valentin) 2500 1800 = 4300 in the "Colaboratori" view. what should I do? Please give me an idea</p>
P粉450079266P粉450079266457 days ago404

reply all(1)I'll reply

  • P粉790187507

    P粉7901875072023-09-05 10:53:19

    You can use the sum in the QueryBuilder.

    像这样:

    $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.

    reply
    0
  • Cancelreply