How to sum elements of a specific person (id) - laravel
P粉450079266
2023-09-04 16:39:02
<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>
You can use the
sum
in the QueryBuilder.像这样:
In your case, you may also use the
withSum
to obtain the result you want. Like so:This resulting Collaborator will have an extra key now named:
projecthistory_sum_suma
which will have the sum of all thesuma
belonging to that Collaborator.This of course assumes that you have a
hasMany
relation with theProjectHistory
model.