How to sum value in laravel relational table column

47 Views Asked by At

eloquent query image here

here I queried from productionActivity model and have relation with productionOutput model. I want to sum output_kg in production_ouputs table from group by data. i have try with withSum() function but it sum from single data not from all group by data

1

There are 1 best solutions below

0
afcyy On

If you are trying to sum the output_kg from the production_outputs table grouped by some data (assuming it's on production_activity table). then the following should work if the groupBy() function is used correctly and the relationship between the models is defined correctly.

ProductionActivity::withSum('productionOutputs', 'output_kg')
        ->groupBy('column_to_group_by') // replace with actual column name
        ->get();