0

I am attempting to write an api endpoint meant to upload many objects of one type. This object, MyObject, contains a lookup field that looks up another MyObject record for translation reasons.

Imagine that I am going to get all of MyObjects in one body, both the original and the translated versions. I know that a look up field is based on Id so I was wondering if I am going to need to create all of the records, insert them in the database, and then after that assign the relationships?

In other words:

// OPTION 1
List<MyObject__c> newObjects = new MyObject__c();
for (bodyObject reqObj : reqBodyObjects) {
    MyObject__c obj = new MyObject__c();
    // set the fields
    obj.translationId = reqObj.translationId;
    newObjects.add(obj);
}
insert newObjects;

for (MyObject__c objA : newObjects) {
    for (MyObject__c objB : newObjects) {
        if (objA.transaltionId == objB.translationId) {
            objA.MyObject__c = objB.Id;
            objB.MyObject__c = objA.Id;
        }
    }
}


// OPTION 2
Map<Decimal, MyObject_c> objList = new Map<Decimal, MyObject__c>()
List<MyObject__c> newObjects = new MyObject__c();
for (bodyObject reqObj : reqBodyObjects) {
    MyObject__c obj = new MyObject__c();
    // set the fields
    obj.translationId__c = reqObj.translationId;
    newObjects.add(obj);

    if (objList.containsKey(obj.translationId__c)) {
        MyObject__c translatedObj = objList.get(obj.translationId__c);
        obj.MyObject__c = translatedObj.Id;
        translatedObj.MyObject__c = obj.Id;
    } else {
        objList.put(obj.translationId__c, obj);
    }

}
insert newObjects;

Is option 2 possible? I don't believe it is because Id doesn't get set until insert, but I wanted to make sure. Or what would be a suggested method of doing this relationship, for example, can you base Look Up objects on a unique field other than Id?

5

It is not possible to insert parent and child records with the statement when the records have the same SObjectType. You will need to insert any parents, then insert or update any children to populate the lookups.

See also the below passage from the Apex Developer Guide (emphasis mine):

Creating Parent and Child Records in a Single Statement Using Foreign Keys

You can use external ID fields as foreign keys to create parent and child records of different sObject types in a single step instead of creating the parent record first, querying its ID, and then creating the child record.

...

You can create related records that are up to 10 levels deep. Also, the related records created in a single call must have different sObject types. For more information, see Creating Records for Different Object Types in the SOAP API Developer Guide.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.