1 回答

TA贡献1788条经验 获得超4个赞
优化的第一条规则(在我看来),
切勿在循环内运行查询。
在循环开始之前:
// Fetch all data at once and use select() whenever possible
$LkpAnswers = LkpAnswer::whereIn('id', collect($answers)->pluck('lkp_answer_id')->toArray())->select('name')->get();
在你的其他条件下(在第二个循环内)做这样的事情。
// Before, this query was inside 2 for loops (n^2). For every n, there's 1 query.
// This right here is a Collection of LkpAnswer::model. Collection is very useful for optimization
$name = $LkpAnswers->where('id', $answer['lkp_answer_id'])->pluck('name')->toArray();
使用它并更改您的第二个 else 条件。仅通过这样做,您将减少近 50% 的运行时间。另请查看有关如何在 laravel 中进行优化的答案。它讨论了缓存、索引、select()和类型转换。
让我在下面的评论中发布。
- 1 回答
- 0 关注
- 83 浏览
添加回答
举报