0

I'm following this page in the documentation for creating parent and child records in a single statement using foreign keys. It works for the Account and Opportunity scenario. But in the scenario wherein the child is not a standard object, it doesn't work.

For example, what I did is:

// The parent
Case parentCase = new Case();
parentCase.ExternalId__c = 'external_id_123abc';

// The case that will act as the foreign key that will connect the parent and the child
Case caseReference = new Case(ExternalId__c = 'external_id_123abc');

// The child
My_Custom_Object__c co = new My_Custom_Object__c();
cs.Name = 'test';
cs.Case__c = caseReference;

This code won't compile because cs.Case__c = caseReference would throw an error of Illegal assignment from Case to Id. Not sure how to go around this error.

The main objective here is to lessen the the soql statements that I need to fire. With this approach, I can create a parent and all of the dynamically created children at runtime.

1 Answer 1

2

The solution turns out to be rather simple, if non-obvious: change cs.Case__c to cs.Case__r.

When you're dealing with relationship fields in Apex, the __c version of the lookup field is typed as an Id value. The __r variant of a lookup field to Some_Object__c is typed as a Some_Object__c, and can be assigned (or extracted as) an sObject class instance in Apex. The __r name of a child relationship is typed as a List<Child_Object__c> and can be interacted with as you'd expect.

These latter two are actually parallel to how standard fields work. Look at the difference in type between Contact.Account and Contact.AccountId, for example, and the type of Account.Contacts. You can safely do someContact.Account.Name (in both SOQL and Apex), and you can do Account a = someContact.Account, but you can't do either of those things with AccountId. It's just that the syntax doesn't make this distinction quite as clear when dealing with custom fields.

0

You must log in to answer this question.

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