The concept is simple that i want to sum some value that name total_hs from table analysis with same workingname. This code running so slow because of foreach if has alot of data. and for model like this Answer You want to return total value for every workingname, If I understand. You can replace your function with the new one