2

The below code is working as expected but can this code be optimized further? and I'm using three different for loops in order to make this working.

I'm trying to find out if the Candidate has attachment associated with the record so each candidate record should associate with one or more attachment.

set<Id> setC = new set<Id> ();
//List<Candidate__c> canAttachList = [SELECT id,name (SELECT Id,Name FROM Attachments) FROM Candidate__c WHERE Employee__c ='XXXXX'];
List<Candidate__c> canAttachList = [SELECT id,name FROM Candidate__c WHERE Employee__c ='XXXXX'];


for(Candidate__c c: canAttachList)
{
  setC.add(c.Id);
}
map<Id, Attachment> mapAttach = new map<Id, Attachment>([SELECT Id,ParentId,Name FROM Attachment WHERE ParentId IN : setC ]);

for(Id c : mapAttach.keySet())
{ 
    for(Id d : setC)
    {
        if(mapAttach.get(c).ParentId == d) {
            system.debug('attachment exists');
        }
        else {
            system.debug('no attachment presents');
        }
    }
}

2 Answers 2

2

use query like

map<id,Candidate__c>  canAttachMap = new map<id,Candidate__c>([SELECT id,name, (select id from attachments) 
FROM Candidate__c WHERE Employee__c ='XXXXX']);

if you know Candidate ID in your code, to check if he has an attachment:

system.debug(canAttachMap.get('XXXXX').attachments.size()>0); 

output is True/False.

Now to show results:

for(Candidate__c candidate:canAttachMap.values())
{
    integer attCounter = canAttachMap.get(ca.id).attachments.size();
    system.debug(candidate.Name + 
    (attCounter > 0 ? ' :
    '+attCounter+' attachment(s) exist.' : 
    ' : no attachment present.'));
}

EDIT: renamed list to map. was bad variable name.

3

Use a subquery

for(Candidate__c c : [SELECT id, name, (Select ID From Attachments) FROM Candidate__c WHERE Employee__c ='XXXXX'])
{ 
    if(!c.Attachments.isEmpty()) {
        system.debug('attachment exists');
    }
    else {
        system.debug('no attachment presents');
    }
}
2
  • Is there way I can get the which candidate has not have attachment? I have tested and if I have two candidate one has attachment and another does not then i want to know which candidate has attachment and which is not.... i have also noticed that its not doing in my code as well.
    – Nick
    Commented Jun 3, 2016 at 1:56
  • Is this an ongoing need? If so use a trigger on attachment to evaluate / set a flag on the candidate when an attachment is inserted or deleted. You can also write a quick batch process to update existing candidate records.
    – Eric
    Commented Jun 3, 2016 at 1:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .