Inserting related objects into the database in Salesforce Apex

Posted on 04-01-2013 10:09 by graham
In Apex, if you have two object which are related to one another through the Master-Detail relationship, you can insert them into the database in one step.

Note This only works with Master-Detail relationships, not with Lookups.

For example, let's say we have two objects:
- Blog_Post__c
- Comment__c

Comment__c contains a lookup field Post__c to the Blog_Post__c object. To insert both a post and its comment in one step, do the following:
Blog_Post__c post = new Blog_Post__c();
post.Title__c = 'Some title';
post.Text__c = 'Some text';

Comment__c comment = new Comment__c();
comment.Text__c = 'Great post!';

// assign both the relationship field "__r" and the ID field "__c"
comment.Post__r = post;
comment.Post__c = post.Id;

// inserting the comment will also insert the post related to it
insert comment;

It is essential to assign both the relationship field Post__r and the ID field Post__c.

Possible errors


If you get the following error while performing this kind of insert:
Cannot specify both an external ID reference Post__r and a salesforce id, Post__c

make sure the objects are associated through a Master-Detail relationship, not a Lookup relationship.
Comments
Hi i am trying to do the same. I have master detail relationship still i am getting this error. "Cannot specify both an external ID reference Post__r and a salesforce id, Post__c".
Added on 06-07-2015 08:37 by anonymous

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems