0

I have a requirement to fetch Parent, Child, and Grandchild and Store them as JSON in the same hierarchy.

Here is my logic:

public List<Parent_Project__c> ProjectRecordsList {get; set;}
    ProjectRecordsList = [SELECT Id, Name,Parent_Project__c, (SELECT Id, Name, (select name from Orders__r) FROM Child_Projects__r) FROM Parent_Project__c];
    string strJSON = JSON.serialize(ProjectRecordsList);

Now the issue here is that, when I run this query, I am getting the error as

SOQL statements cannot query aggregate relationships more than 1 level away from the root entity object.

I could able to fetch Parent Project and its child Project successfully whereas when I include Orders (Grandchild), I am seeing this error. I know that I can write queries 5 levels up if I start with Child but in this case, I need to fetch the records starting from Parent to Grandchild.

Can anyone please let me know how to add Orders of Child Projects in the JSON?

2
  • what's the context of this query? Are you trying to get a whole picture of every single project or is this running within a trigger/code where there's a subset of project Ids you're interested in? Jul 4, 2021 at 15:32
  • I want to get all the Parent Projects and its child projects along with Orders related to child projects. Parent Project will be the parent branch, followed by Child branch and Order branch. On the whole, the record count is like 500 or 600 from parent to grand child
    – SFDCUser
    Jul 4, 2021 at 15:40

1 Answer 1

1

Understanding Relationship Query Limitations

In each specified relationship, only one level of parent-to-child relationship can be specified in a query. For example, if the FROM clause specifies Account, the SELECT clause can specify only the Contact or other objects at that level. It could not specify a child object of Contact.

About generating Json from Parent to Grandchild you can look for fflib github source code

fflib_ApexMocksUtils

You must log in to answer this question.

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