Hello how do i sum table column for specific person (id). For example i have a table like this(this is table ProjectHistory table):
and i want to display in my colabs view, all sum with specific collaborator so for example look image below.(this is Collaborators table)
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
CodePudding user response:
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.
CodePudding user response:
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');
}
and then add the array projectHistory, in your view.