function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Paul FoleyPaul Foley 

Am I able to remove my Apex nested loops?

Hi All,

I'm putting together an invocable Apex method that gets called when an order is Activated.
The method loops around the products in the order (OrderItems) and create X number of Assets based on the quantity value of the order line.
This means I end up with a loop inside a loop. I'm not hitting limits yet, but am concerned that I could once we move the code to production.

Here's the offending code:
for(OrderItem prod : [select OrderItem.Product2.name, CurrencyIsoCode, id, Product2Id, Quantity, UnitPrice, OrderItem.Order.AccountId, OrderId from OrderItem where OrderId in : oids and OrderItem.Pricebookentry.product2.Is_Asset__c = true]){
            for (integer i = 0; i < prod.Quantity; i++) {
                Asset a = new Asset();
                a.name = prod.Product2.name;
                a.AccountId = prod.Order.AccountId;
                a.Price = prod.UnitPrice;
                a.Product2Id = prod.Product2Id;
                a.Quantity = 1;
                a.CurrencyIsoCode = prod.CurrencyIsoCode;
                a.Status = 'Purchased';
                a.Order_Product__c = prod.id;                

            	newAssets.add(a);
            }
        }

insert newAssets;



 
Best Answer chosen by Paul Foley
John TowersJohn Towers
The pattern you're using is pretty much the accepted practice: Loop through whatever you need and collect a single list of objects to perform an action on and then perform the action after you've compiled the entire list.

You would have problems if your insert statement was inside of a loop but you've avoided that so you should be safe.

All Answers

John TowersJohn Towers
The pattern you're using is pretty much the accepted practice: Loop through whatever you need and collect a single list of objects to perform an action on and then perform the action after you've compiled the entire list.

You would have problems if your insert statement was inside of a loop but you've avoided that so you should be safe.
This was selected as the best answer
Paul FoleyPaul Foley
Thanks John, I figured that might be the answer.