I have a callout which receives one master object which I map to a Case and upsert base on a field set as External Id. Inside this master object there is a list of child objects which I map to a custom object that is the detail side of a master-detail relationship with Case. I'm successfully saving upserting the case by using the External Id field. My problem is when I try to upsert the custom object passing the case. Salesforce throws an error saying I'm missing the required field.
How do I use the case External Id field when relating it to the child object?
Below is the code I'm trying to make use:
List<Case> casesToUpsert = new List<Case>();
List<Comentario_Reclame_Aqui__c> crasToInsert = new List<Comentario_Reclame_Aqui__c>();
for (ReclameAquiDTO.TicketDTO ticket : tickets) {
Case c = new Case();
c.Reclame_Aqui_Id__c = ticket.id; //external Id field
c.Status = ticket.status;
for (ReclameAquiDTO.InteractionDTO interaction : ticket.interactions) {
Comentario_Reclame_Aqui__c cra = new Comentario_Reclame_Aqui__c();
cra.Case__r = c; // Relational field (Master-detail);
cra.Message__c = interaction.message;
crasToInsert.add(cra);
}
}
Database.upsert(casesToUpsert);
Database.insert(crasToInsert);
I kept only the relevant information.
When I try the code above, the following error occurs:
Required fields are missing: [Case__c];getStatusCode=REQUIRED_FIELD_MISSING;
The error itself is pretty obvious, but I can't understand why it's happening. I followed the example from the Salesforce Documentation.
How should I implement the logic?