How to do a multi-level relationship query on Chatter/Comments

Trying to perform a SOQL query to retrieve related FeedItems and FeedComments (on the related FeedItems) to my sObject and I retrieved a warning that multi-level queries aren’t allowed.

Can anyone think of an optimization that will reduce the risk of overflowing script statements and allow me to retrieve related FeedItems and the FeedComments related to those items

List<myObject> sObjectsWithComments = [SELECT Id (SELECT Id,Body,ParentId, (SELECT 
                                       Id, CommentBody, FeedItemId FROM FeedComments) FROM
                                       Feeds) FROM myObject];

If this isn’t achievable it’s still possible to manually selected the FeedComment and create a map, and do a manually association, but I really think this is something the database should be responsible for.


I guess I should also mention some of the difficult requirements:

  1. List item: In any given instance the page I’m working with may have
    over 100 object records
  2. I need count the number of FeedItems and FeedComments that have been created by another user since a LastVisit__c field on the parent object. Hence the issue with looping

So I have a goal of something more akin too (psuedo-code):

List<myObject> sObjectsWithComments = [SELECT Id,LastVisit__c (SELECT Id,Body,ParentId, (SELECT 
       Id, CommentBody, FeedItemId, CreatedDate FROM FeedComments WHERE CreatedDate > Parent.LastVisit__c) FROM
       Feeds WHERE CreatedDate > Parent.LastVisit__c) FROM myObject];


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Separate the feed from the object to avoid a nested query.

List<FeedItem> feedWithComments = [SELECT Id,Body,ParentId, (SELECT 
                                   Id, CommentBody, FeedItemId FROM FeedComments) FROM
                                   FeedItem WHERE ParentId IN (SELECT Id FROM
                                   myObject WHERE Field = 'value')];

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x