[SalesForce] Unable to Add Child Object to a Parent Object List

I queried a the parent object and its Kid(Kid__C). Assigned it to a list of Parent object:

List<Parent__c> p = [SELECT id, name (SELECT id, name FROM kids__r order by CreatedDate DESC),
            FROM Parent__c WHERE id IN: AlistWithParentId];

// After qurying the above list , I check which parent does not have children using p.kids__r.size(); and create a kid for them. After
I do this I want to add the kid's id to the p.kids__r list of each element in List<Parent__c> p. Basically I do not want to make another SOQL to fetch
the parent__c records from database instead use the already queried List<Parent__c> p to get the kids.

I tried an approach where I created a Map with parent id and with list of ids of the kid but I am unable to add it to the p.kids__r list.

For(Parent pobj : p){

// loop through the Map and get the list of
// RMA orders and add it to pobj.kids__r.add();

pobj.kids__r.add(kid__c);
system.debug(ponj.kids__r.size()); // this gives the size as 0, that means the above line of code did not add the kid to the list.
pobj.Name='hello';
system.debug(pobj.Name); // this gave me the name as hello. Why was this variable updated but above list could not be?

}

Best Answer

I believe your only option is to re-query. Unless you want to do some crazy serialization hijinks like I laid out in this other post. Basically, you would probably have to do something like the following:

class Proxy
{
    final List<Child__c> records;
    Proxy(List<Child__c> children) { records = children; }
    Integer totalSize { get { return records.size(); } }
    Boolean done = true;
}

// elsewhere...
Map<String, Object> data = parent.getPopulatedFieldsAsMap();
data.put('ChildRelationshipName__r', new Proxy(allChildren));
parent = (Parent__c)JSON.deserialize(JSON.serialize(data), Parent__c.class);