1 回答

TA貢獻1788條經驗 獲得超4個贊
優(yōu)化的第一條規(guī)則(在我看來),
切勿在循環(huán)內運行查詢。
在循環(huán)開始之前:
// Fetch all data at once and use select() whenever possible
$LkpAnswers = LkpAnswer::whereIn('id', collect($answers)->pluck('lkp_answer_id')->toArray())->select('name')->get();
在你的其他條件下(在第二個循環(huán)內)做這樣的事情。
// 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 中進行優(yōu)化的答案。它討論了緩存、索引、select()和類型轉換。
讓我在下面的評論中發(fā)布。
- 1 回答
- 0 關注
- 98 瀏覽
添加回答
舉報