【问题标题】:Can I insert deserialized JSON SObjects from another Salesforce org into my org?我可以将来自另一个 Salesforce 组织的反序列化 JSON SObject 插入我的组织吗?
【发布时间】:2012-10-27 17:21:45
【问题描述】:

我们需要将复杂的数据结构从一个组织克隆到另一个组织。这包含一系列自定义 SObject,包括父母和孩子。

流程如下。在 origin org 上,我们只是 JSON.serialize 我们想要发送的 SObject 列表。然后,在目标组织上,我们可以 JSON.deserialize 该对象列表。到目前为止一切顺利。

问题是我们不能直接插入这些 SObject,因为它们包含原始组织的 ID,而 Salesforce 不允许我们插入已经有 ID 的对象。

我们找到的解决方案是手动插入对象层次结构,维护 originId > targetId 的映射并手动修复关系。但是,我们想知道 Salesforce 是否提供了一种更简单的方法来做这样的事情,或者有人知道更好的方法来做这件事。

Salesforce 中是否有嵌入式方式来执行此操作?还是我们陷入了繁琐的手动流程?

【问题讨论】:

    标签: json salesforce


    【解决方案1】:

    List.deepClone() 调用 preserveIds = false 可能会处理一个问题,那么:

    考虑使用 upsert 操作为您建立关系。 Upsert 不仅可以防止重复,还可以maintain hierarchies。 您需要在父级上使用外部 Id 字段,而不是在子级上。

    /* Prerequisites to run this example succesfully:
        - having a field Account_Number__c that will be marked as ext. id (you can't mark the standard one sadly)
        - having an account in the DB with such value (but the point of the example is to NOT query for it's Id)
    */
    Account parent = new Account(Account_Number__c = 'A364325'); 
    Contact c = new Contact(LastName = 'Test', Account = parent);
    upsert c;
    
    System.debug(c);
    System.debug([SELECT AccountId, Account.Account_Number__c FROM Contact WHERE Id = :c.Id]);
    

    如果您不确定它是否适合您 - 使用 Data Loader 的 upsert 功能,可能有助于理解。

    如果您在同一个 sObject 类型上有超过 2 个级别的层次结构,我认为您仍然必须以正确的顺序更新它们(或使用 Database.upsert 版本并继续为失败的那些重新运行它)。

    【讨论】:

      猜你喜欢
      • 2017-02-23
      • 2020-10-14
      • 2020-10-08
      • 2021-11-02
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      相关资源
      最近更新 更多