Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
    
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 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 at 10:00
    
Thanks, enabling email-to-case did it for me –  vishesh May 10 at 10:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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