修改Master-Details类型字段的值
在salesforce中,master-detail字段值必填,且后面不可更改,可以将sobject转成map进行更改。
Savepoint sp = Database.setSavepoint();
OpportunityLineItem line = [select id, OpportunityId from OpportunityLineItem where OpportunityId != null limit 1];
Opportunity oppty = [select id from Opportunity where id != :line.OpportunityId limit 1];
//line.Opportunity = oppty.Id; 报错, master details关系不可修改master id
System.debug(LoggingLevel.DEBUG, '*** Opportunity1: ' + line.OpportunityId);//旧的master id
//先把子对象转json字符串,再把json字符串转成Object,再把Object转map,
Map<String, Object> mp = (Map<String, Object>)(JSON.deserializeUntyped(Json.serialize(line)));
//修改master id
mp.put('Opportunity', oppty.Id);
//map转json, json再转子对象
OpportunityLineItem line2 = (OpportunityLineItem)Json.deserializeStrict(Json.serialize(mp), OpportunityLineItem.class);
//更新子对象,这样就能更改mater id了
update line2;
System.debug(LoggingLevel.DEBUG, '*** Opportunity2: ' + line2.OpportunityId);//
Database.rollback(sp);