1

I want to get the associated CaseComment's CommentBody for a list of cases.

String queryFields = 'Id, Subject, CaseComment.CommentBody';
 List<Case> cases = Database.query('select '+ queryFields +' from Case');
 for(Case c: cases){
       System.debug(c.CaseComment.CommentBody);
 }

but this doesn't work as there is no reference in Case object for the CaseComment. CaseComment has the field parentId which stores id of associated Case. How can I get CaseComment. I don't want to query the CaseComment object for each case in a loop.

5

You must traverse the child relationship CaseComment, for example:

List<Case> cases = [Select (Select Id, ParentId, IsPublished, CommentBody, CreatedById, CreatedDate, SystemModstamp, LastModifiedDate, LastModifiedById, IsDeleted From CaseComments) From Case ];

for(Case c : cases)
{
    for(CaseComment comm : c.CaseComments)
    {
        System.debug(comm.CommentBody);
    }
}

This is because there are many Case Comments to one Case, i.e. a one to many relationship between case and comment as per the master/detail or lookup relationship.

You should consider using Eclipse schema viewer so that you can find these relationships out yourself, its a simple point/click interface so you can traverse them graphically.

  • Thanks for you answer. I also need EmailMessage associated with case. In EmailMessage object (salesforce.com/us/developer/docs/api/Content/…) I see a ParentId field that says 'id of parent case', but in eclipse Schema viewer I don't see any child relationship for email messages – vishesh May 10 '14 at 9:48
  • 1
    Same deal, [select id, (select id from emailmessages) from case] but I think you have to enable 'Email To Case' in org to see the object – Phil Hawthorn May 10 '14 at 10:00

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.