Home > Software design >  My Laravel Code running slow because foreach, should i change my query to chunk? and how to optimize
My Laravel Code running slow because foreach, should i change my query to chunk? and how to optimize

Time:12-15

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 App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

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',
    ];
}

CodePudding user response:

try this

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

CodePudding user response:

You want to return total value for every workingname, If I understand. 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;
}
  • Related