3

I'm getting a parent record which is Account acc, and a list of Contacts listContact from another process.

Now in order to proceed further I need to do something I could do like:

Account acc = [select Id, (select Id from Contacts) from Account limit 1];

I tried to do acc.Contacts = listContact; which is a compile time error. (Field is not writeable: Account.Contacts)
I am able to do acc.Contacts.addAll(listContact); but when I access/print acc.Contacts, it returns nothing.

Is there any way to assign the related child record to the parent variable?

5

This is not supported as of now, whereas you can set the parent object using putSObject(fieldName, value). But there is no function like putSobjects() to set the child records, again you can get the child objects using getSObjects(fieldName).

To overcome your problem, either you can create a Map<Id, Contact[]>, or a wrapper class. Using a map is useful for most of the cases, while the wrapper is needed if you are iterating this data on UI.

Refer SObject Class

1
  • 1
    Yeah I knew about the map solution, and now I need to make changes in the whole method. as my method is being called from another place as well, where I am querying, but my current implementation sends data itself. I tried to play with JSON serialize and deserialize as well, which I didn't find nice. Thanks for the answer..! – Aditya Vijay Jun 12 '20 at 7:22

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.