在salesforce中有个特殊的用户,就是__r,无论实在apex代码还是在soql语句中,都可以使用__r关联出关联对象中的字段出来。在获取数据的时候十分方便。
今天要介绍在apex class中的一种用用法。
例如在一个场景下,在某医药公司的CRM系统中,需要通过导入数据批量创建一批医生和科室,并且需要将医生所属的科室关联在一起。在这个场景下,需要创建一个新的医生(Person Account),和医生所属的科室(Account)。医生和科室都是Account,只是RecordType不同,并且都有External Id作为唯一的系统标识。编写代码如下:
trigger DCRAfterUpdateInsert on DCR__c (after update,after insert) {
List<Account> newDepAccounts = new List<Account>();
List<Account> newHCPAccounts = new List<Account>();
Id depRecordtypeId = sobject.account.....;//get dep recordtype id
Id hcpRecordtypeId = sobject.account.....;//get hcp recordtype id
for(DCR__c tempDcr : trigger.new)
{ //new dep account,required field must not empty
newDepAccounts.add(new Account(
Account_External_Id__c = tempDcr.Dep_Externla_Id__c,
recordtypeid = depRecordtypeId,
Name = tempDcr.DepName));
// new HCP
Account newHCPAccount = new Account();
newHCPAccount.LastName = tempDcr.HCP_LastName__c;
newHCPAccount.recordtypeid = hcpRecordtypeId;
newHCPAccount.Account_External_Id__c = tempDcr.HCP_External_Id__c;
newHCPAccount.DEP_Account__r = new Account(Account_External_Id__c = tempDcr.Dep_Externla_Id__c);//hcp references dep
newHCPAccounts.add(newHCPAccount);
}
if(newDepAccounts.size() > 0 )
upsert newAccounts Account_External_Id__c;
if(newHCPAccounts.size() > 0 )
upsert newCases Account_External_Id__c;
}
这种方式是最简便的方式,有如下几点需要注意:
1.depAccount 和HCPAccount 插入的顺序不能颠倒。否则报错。“INVALID_FIELD, Foreign key external ID: testAccount not found for field Account_External_Id__c in entity Account”
2.__r后面赋值的时候,new Account(此处只能对External Id类型的赋值。),否则保存,如对Name赋值:"INVALID_FIELD,Name is not an External ID or indexex field for Account"
参考文档:Creating Parent and Child Records in a Single Statement Using Foreign Keys
不能适用,auto number 作为external id的时候。