嵌套循环导致性能降低

时间:2018-05-24 08:39:07

标签: laravel loops nested-loops

foreach ($id_prs as $ids) {
   list($id_pr, $id_cart) = explode('-', $ids);
    foreach ($id_cart as $id) {
        $r = Cart::find($id);
                /// column to update value
                $r->save();
    }
}

这就是我的循环的样子。

E.g。 $ id_prs由10个数据组成,而每个id_prs可能包含20个数据等。

从那里,我发现从每个$ id_cart获取大量数据时需要更长的时间来循环。

如何解决性能问题,有什么解决方案吗?

3 个答案:

答案 0 :(得分:1)

这被称为n + 1问题,每次在foreach内部迭代时都会创建其他查询。

所以这条线是邪恶的,因为它每次迭代都会查询数据。

$r = Cart::find($id);

你可以做得更好:

$cart = Cart::all();
foreach ($id_prs as $ids) {
   list($id_pr, $id_cart) = explode('-', $ids);
    foreach ($id_cart as $id) {
        // Get it from collection rather than query it from database
        $cart->where('id', $id)->first()->save();
    }
}

您可以将变量内的所有购物车作为集合进行查询,并且只需在不触及数据库的情况下使用该集合进行操作(仅当您点击保存方法时)。

答案 1 :(得分:0)

您的代码和变量不够清晰。但更好的解决方案是:

foreach ($id_prs as $ids) {
   list($id_pr, $id_cart) = explode('-', $ids);
   $items = Cart::whereIn('id', $id_cart) -> get();

   foreach($items as $item) {
       Cart::where('id', $item -> id) -> limit(1) -> update([
           // Columns to update
       ]);
   }
}

答案 2 :(得分:0)

如果要为所有记录更新相同的值

BEGIN -- first update to check Interface held SMR and Interface held SMA
update interface set INTERR = 'U7'
from interface i
where 
i.conttype = 'SMR' 
and isnumeric(i.contrate)=1 
and cast(i.contrate as decimal(12,2)) < 5 
and caseno = @caseno
and exists (
    select 1 
    from interface i2 
    where i2.caseno = @caseno 
    and isnumeric(i2.contrate)=1 -- This was moved up
    and i2.conttype = 'SMA' 
    and i2.intmembno = i.intmembno 
    and i2.effdte = i.effdte 
    and i2.contrate > cast(0 as decimal(12,2))
)