+ Start a Discussion
Richie DRichie D 

Adding a child record to a relationship list

Dear all,

 

Can anybody explain to what the contact 'me' is added to in the code below?

Account a = [select id, name ,(select id, name from Contacts) from Account limit 1];
system.debug(a.contacts);
Contact me= new contact(lastname='smith', firstName='bob', accountId=a.Id);
a.contacts.add(me);
system.debug(a.contacts);

 Both system.debug statements will show the same records before and after adding me to the collection. Presuming that the collection 'Contacts' is somehow a read-only list; no error is found when running. So, has the add method call been ignored or just somehow adding to the 'wrong collection'...

 

This isn't a problem that needs fixing but may get you wondering like me ;)

 

Cheers,

Rich.

steve456steve456

List of all contacts under the account are retrieved

 

 

-----Smith------

This particular contact has been added to existing list of contacts of that particular account

dmchengdmcheng

You have to insert the contact record first, for certain.  If you then add it to a.contacts it might work, but I think you will have to re-query the account.

craigmhcraigmh

Yeah, you're only adding it to the Contacts list that's in memory, not in the DB.