function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
TsukasaTsukasa 

New insert using relations

Posting this question again just going to try and reword it differently since I can't seem to find an answer.

Senario

Tables

 

Asset
AssetServices__c (linked to Asset)
....etc

 

when I have a new asset that doesn't have a sales force ID, how do I upsert the Asset and AssetServices

Here is what i'm doing in code

 

//get account and create asset
Account account = (Account)qr.records[0];
Asset asset = new Asset();

//search for account and assign asset to it
asset.AccountId = account.Id;

...assign asset details

//create services
AssetServices__c services = new AssetServices__c()

..assign stuff

..upsert

 

The problem is if the asset doesn't exist already I have no ID to assing to AssetServices__c.

I am having to do my upserts twice in a row to get my data in.

 

Any help would be great

Thanks

sfdcfoxsfdcfox
If you're unsure if the asset exists, then yes, you would have to insert it, then insert the related asset services. Salesforce will not magically create an asset for assetservices record without a second call.

That said, you COULD write webservice Apex Code function that accepts all the necessary parameters for the account, asset, and asset service, and then call that single function from your program. This would reduce the number of API calls accordingly by moving the payload to the Salesforce servers.
JWykelJWykel

As far as I'm aware, the only way for you to create a parent and child at the same time is by using an external Id field.

Something like this:

Asset asset = new Asset();
asset.MyExternalId__c = "123";
asset.AccountId = account.Id;
asset.Details__c = "Assign everything else as you would.";

AssetServices__c services = new AssetServices__c();
services.Asset__r = new Asset(){ MyExternalId__c = "123" };
services.Stuff__c = "Assign everything else as you would.";

sfdc.create(new sObject[]{ asset, services });
//OR//
//sfdc.upsert(new sObject[]{ asset, services });

 The key points:
You have to use an external Id if you want to insert both parent and child records in a single call.

The parent must come *before* the child in the sObject list for create/upsert.