Crazy
Crazy

Reputation: 867

Nested loop caused slow in performance

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

This is how my loop looks like.

E.g. $id_prs consist of 10 data, while each id_prs may consist of 20 data etc.

From there, i found will take longer time to loop when a lots of data from each $id_cart.

How can i solve the performance issue, is there any solution?

Upvotes: 0

Views: 862

Answers (3)

Lukáš Irsák
Lukáš Irsák

Reputation: 1132

This is known as n+1 problem, every time you iterate inside foreach additional query is created.

So this line is the evil, because it's querying data every iteration.

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

You can make it better like this:

$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();
    }
}

Where you acctualy query all carts inside variable as a collection, and you just manipulating with that collection localy without touching database (only when you hit save method).

Upvotes: 1

DsRaj
DsRaj

Reputation: 2328

If you want to update same value for all the records

$allIds = [];
foreach ($id_prs as $ids) {
   list($id_pr, $id_cart) = explode('-', $ids);
    foreach ($id_cart as $id) {
        $allIds[] = $id;
    }
}
$cart = Cart::whereIn('id',$allIds)->update(['columns'=>'value']);

Upvotes: 0

AliN11
AliN11

Reputation: 2573

Your code and variables are not clear enough. But a better solution is:

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

Upvotes: 0

Related Questions