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
Maciej SobkowiczMaciej Sobkowicz 

Create Asset hierarchy in single REST API call - Parent and child assets

Hi all,

I would like to create Asset hierachy with a single REST API call, providing root Asset and his child Assets (https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/dome_composite_sobject_tree_create.htm)
I can't do this because it seems that Asset.ParentId field doesn't have relationship name

User-added image

I tried to guess relationship name but with no success.

Here is my sample request body:
 
{
    "records": [{
        "attributes": {"type": "Asset"},
        "Name": "Site Nested",
        "AccountId": "someId",
        "ChildAssets": {
            "records": [{
                 "attributes": {"type": "Asset"},
                 "Name": "Device Nested 1",
                 "AccountId": "someId"
            },{
                 "attributes": {"type": "Asset"},
                 "Name": "Device Nested 2",
                 "AccountId": "someId"
            }]
        }
    }]
}

Do you have any idea how this can be achieved?
Maciej SobkowiczMaciej Sobkowicz
Is there any option besides creating new custom field and using it in REST api call to build hierarchy?
DanCurryJrDanCurryJr
You might consider creating a map of parents with children first, then making that your output
public class assetOutput {
  public asset record {get; set;}
  public asset[] children {get; set;} 
}

public map<id, assetOutput> output {get; set;}

public void buildOutput(string accountid){
  this.output = new map<id, assetOutput>();
  for(asset a : [select id, name, parentId from Asset where accountId = :accountid] order by parentId nulls first){
    if(this.output.get(a.id) == null){
      assetOutput tmp = new assetOutput();
      tmp.record = a;
      tmp.children = new asset[]{};
   }
   if(a.parentId != null){
    if(this.output.get(a.parentId) != null){
      this.output.get(a.parentId).children.add(a);
    }
   }
  }
}

public string value(){
  string acid = ''; //ID of the Account you want to get assets for, however you want to get that with the service
  buildOutput(accId);
  return JSON.serialize(this.output);
}

 
DanCurryJrDanCurryJr
@line 25 should be 'accId', not 'acid'.