0

Below is my code

        for(object__c conv: database.query(query)){
            List <Attachment> attachmentList = [SELECT Id, Name, ContentType, ParentId FROM Attachment WHERE ParentId = :conv.Id limit 1];  
            if (attachmentList.size() > 0){
                Attachment att = attachmentList[0];
                row.AttachmentId = att.Id;
                row.AttachmentName = att.Name;
                row.AttachmentType = att.ContentType;
            }

This Code gives me the

Too Many SOQL Queries 101 exception

so I have updated it as below

        list <Attachment> attachmentList = [select Id, Name, ParentId from Attachment];
        for(object__c conv: database.query(query)){  
            for (Attachment att : attachmentList){
                if (conv.Id == att.ParentId){
                    row.AttachmentId = att.Id;
                    row.AttachmentName = att.Name;
                    row.AttachmentType = att.ContentType;
                }
            }

but this code gives me below error

exceeded 100000 distinct ids

What can I do to solve the issue?

Thanks in advance

1

So do like this

first query the object and store into list

List<object__c>  lstconv = database.query(query);

after that based on this list only get only their attachments

list <Attachment> attachmentList = [select Id, Name, ParentId 
                                      from Attachment WHERE ParentId IN: lstconv];

after that iterate over the attachment and create row (don't know what it is)

for (Attachment att : attachmentList)
{
    row.AttachmentId = att.Id;
    row.AttachmentName = att.Name;
    row.AttachmentType = att.ContentType;
}
| improve this answer | |
0

You could use a sub-query in your SOQL, which has a distinct advantage of memory usage and processing time. Here's what that would look like:

for(Object__c parentRecord: [SELECT (SELECT Name, ContentType FROM Attachments) FROM Object__c) {
  for(Attachment attachmentRecord: parentRecord.Attachments) {
    row.AttachmentId = attachmentRecord.Id;
    row.AttachmentName = attachmentRecord.Name;
    row.AttachmentType = attachmentRecord.ContentType;
  }
}

Note that you don't need to check if a list is empty before you iterate over it; this code would work just fine if the Object__c were updated to the name of object you're using.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.