在 laravel 中使用 group by 时处理代码很慢?

Processing code is slow when using group by in laravel?

我在laravel处理,producttable有300,000 items处理。那个table里面有很多重名,所以我用了groupBy。但是需要很长时间来处理。一旦我加载页面并等待它完成数据处理,它也需要大约 6 秒到 7 秒。有什么办法可以快速优化吗,谢谢

$listProduct = Product::all()->groupBy('name'); // It takes about 6 seconds to 7 seconds to process this

当您按此顺序调用 groupBy 函数时,您指的是一个 Collection 对象,该对象试图对它收到的所有模型进行分组。模型是相对较大的对象,因此需要花费大量时间。更好的解决方案是在数据库一侧进行分组,这样可以更有效地执行此类变化。

Product::all()->groupBy('name'); // slow group by on collection returned by all() method

Product::groupBy('name')->get(); // fast group by on database side