I'm pretty new on apex. I'm writting an apex class to load a csv file and I need to process the data before to insert on a custom object, each record contains account's name but the field has to be the account's id, so I have a big SOQL with id and names of accounts and I need to search on a big list the name to get the id. If I use a for loop I get the cpu time error so I tried to use map to store the data, but I want the Id and the method get() needs de id to return de value. Is there a way to get the id using the name? or use the name as key in the map and the id as value. Thanks
-
1without posting code to show what you tried, you are asking community to do your work for you which is not part of this forum's mission. Keep your code to a minimum and clearly indicate where you are stuck– cropredyJul 10, 2015 at 16:22
-
1not sure what you're doing, but if you use upsert then you can use an externalId to either insert/update your related data or to insert/update the account record itself. just define a text field on the account as external Id and make sure it has the right cross-reference value - here it sounds like you're using the name (I don't recommend this, but if the shoe fits...).– Caleb SidelJul 10, 2015 at 17:11
1 Answer
You can create a map from the name to the ID like this (where names
is the set of names from your CSV; if the number of Accounts is small you won't need that where
term):
Map<String, Id> m = new Map<String, Id>();
for (Account a : [select Id, Name from Account where Name in :names]) {
m.put(a.Name, a.Id);
}
and then when you do a get
using a name from the CSV the ID will be returned.
Note that this arrangement relies on all Accounts having unique names.