Skip to content
Advertisement

My Laravel Code running slow because foreach, should i change my query to chunk? and how to optimize it?

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.

public function totalHSBySameName()
    {

        $result = Analysis::selectRaw('workingname')->get();

        $name = [];
        $total = [];
        
        foreach ($result as $i) {
            if (!in_array($i->workingname, $name)) {
                $name[] = $i->workingname;
            }
        }
        foreach ($name as $i) {
            $temp = 0;
            $x = Analysis::selectRaw('workingname,total_hs')
            ->where('workingname', $i)
            ->get();
            foreach ($x as $j) {
                $temp += $j->total_hs;
            }
            $total[] = ["name" => $i, 'total_hs' => $temp];
        }
        return $total;
    }

and for model like this

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Analysis extends Model
{
    use HasFactory;

    protected $analysis;
    public $table = 'analysis';
    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';
    protected $fillable = [
        'workingname',
        'code',
        'koef',
        'total_hs',
        'created_by',
        'updated_by',
    ];
}

Advertisement

Answer

You want to return total value for every workingname, If I understand. You can replace your function with the new one that I mention below.so, It’s might be helpful:

public function totalHSBySameName() {
        $result = Analysis::groupBy('workingname')
            ->selectRaw('sum(total_hs) as sum, workingname')
            ->pluck('sum','workingname');

        return $result;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement