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
Sylvio AvillaSylvio Avilla 

Bulkfy Sample Code

Hello,

I would like some help to bulkify the code bellow:
 
for (Trip__c trip : trigger.new )
{
	List<Trip__c> myTrips = [Select ID from Trip__c WHERE day__c =:trip.Day__c 
                            and driver__c =:trip.driver__c];

    .... rest of the code ....
}
Thanks
 
AmulAmul
Using collection we can do this. Please let me know your full requitement i cn help you.
Sylvio AvillaSylvio Avilla
Hy Amul,

The problem is that my SOQL is inside the Loop... can you explain in more details how can I move it outside?

Thanks
AmulAmul
1. Create a new field called Key__c as Formula Text which will Trip__c.Day__c +''+ Trip__c.Driver__c set setdriverDayKey=new set(); string strKey; for (Trip__c trip : trigger.new ) { strKey=trip.Day__c + '' + trip.driver__c; setdriverDayKey.add(strKey) } List myTrips = [Select ID from Trip__c WHERE Key__c in:setdriverDayKey]; hope this will help you.
AmulAmul
1. Create a new field called Key__c as Formula Text which will Trip__c.Day__c +''+ Trip__c.Driver__c



set<string> setdriverDayKey=new set<string>();


string strKey;
for (Trip__c trip : trigger.new )
{

    strKey=trip.Day__c + '' + trip.driver__c;
    
    setdriverDayKey.add(strKey)
    

}


List<Trip__c> myTrips = [Select ID from Trip__c WHERE Key__c in:setdriverDayKey];
JeffreyStevensJeffreyStevens
I would code it like this...


// Collect all drivers from triggered trips
set<id> driverIds = new set<id>();
for(Trip__c trip :trigger.new) {
    driverIds.add(trip.Driver__c)
}

// Get all trips for the Drivers that were triggered and put in a map of <DriverID,list<Trip__c>>
map<id,list<Trip__c>> mDriverTrips = new map<id,list<Trip__c>>();
list<Trip__c> tripsToProcess = new list<Trip__c>([SELECT id,Day__c,Driver__c FROM Trip__c WHERE Driver__c IN :driverIds);
for(Trip__c trip :tripsToProcess) {
    list<Trip__c> iterTrips = new list<Trip__c>();
    if(mDriverTrips.containsKey(trip.Driver__c) {
        iterTrips = mDriverTrips.get(trip.Driver__c);
    }
    iterTrips.add(trip);
    mDriverTrips.put(trip.Driver__c,iterTrips);
}

// Now you have a map of <DriverID, List<Trip__c>>  - and you've only used 1 SOQL - and it's bulkified