Limit jumlah query pertransaksi di apex sejumlah 100, jadi hati-hati untuk penggunaan query, contohnya hindari query didalam loop, alternatifnya kita bisa query semua data yang diperlukan terlebih dahulu diluar loop, sehingga fungsi loop hanya untuk mengolah data extrak dari query sebelumnya.
dibawah adalah contoh code yang kurang efisien, menyebabkan error max 100 query per transakasi atau 150 dml.
trigger accountTestTrggr on Account (before insert, before update) { //For loop to iterate through all the incoming Account records for(Account a: Trigger.new) { List<Contact> contacts = [select id, salutation, firstname, lastname, email from Contact where accountId = :a.Id]; for(Contact c: contacts) { //akan mengabibatkan error jika query lebih dari 100
//contoh query ke object lain
ObjectLain__c ol = [select id,name from ObjectLain__c where contactId = :c.id];
//akan mengakibatkan error jika contact lebih dari 150
update c;
}
}
}
Dibawah adalah contoh code yang lebih efisien, yaitu query langsung account dengan contact yang kemudian di oleh didalam loop tanpa query object contact.
trigger accountTestTrggr on Account (before insert, before update) { //This queries all Contacts related to the incoming Account records in a single SOQL query. //This is also an example of how to use child relationships in SOQL List<Account> accountsWithContacts = [select id, name, (select id, salutation, description, firstname, lastname, email from Contacts) from Account where Id IN :Trigger.newMap.keySet()]; List<Contact> contactsToUpdate = new List<Contact>{}; // For loop to iterate through all the queried Account records for(Account a: accountsWithContacts){ // Use the child relationships dot syntax to access the related Contacts for(Contact c: a.Contacts){ System.debug('Contact Id[' + c.Id + '], FirstName[' + c.firstname + '], LastName[' + c.lastname +']'); c.Description=c.salutation + ' ' + c.firstName + ' ' + c.lastname; contactsToUpdate.add(c); } } //Now outside the FOR Loop, perform a single Update DML statement. update contactsToUpdate; }
Tidak ada komentar:
Posting Komentar