我的 Laravel 代码 运行 很慢,因为 foreach,我应该将查询更改为块吗?以及如何优化它?

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

这个概念很简单,我想用相同的工作名称从 table 分析中总结一些名称为 total_hs 的值。这段代码 运行 很慢,因为 foreach if 有很多数据。

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;
    }

对于这样的模型

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

试试这个

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

你想 return total 每个 workingname 值,如果我明白的话。 您可以用我提到的新功能替换您的功能 below.so,这可能会有所帮助:

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

        return $result;
}