You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Salesforce Apex代码问题:列表重复保存单条SObject记录

问题排查与修复方案

问题根源

你在循环外部仅初始化了一个Domain_review__C类型的对象PRrecordupdate,每次匹配到条件时,只是修改这个同一个对象的属性值,再将它添加到列表PRCollectionupdate中。由于列表存储的是对象的引用而非副本,列表里所有元素指向的都是同一个内存地址的对象。每次修改该对象属性,列表中所有已添加的元素都会同步变化,最终列表里只会保留最后一次修改后的对象重复项。

修复代码

将PRrecordupdate的实例化操作移到if条件内部,确保每次匹配时都创建一个新的对象实例:

List<Domain_review__C> newPR = new List<Domain_review__C>();
List<Domain_review__C> PRCollectionupdate = new List<Domain_review__C>();
map<id,domain_review__C> PRmap = new map<id,domain_review__C>();    

List<Domain_Review__c> PR  =  [Select id,name,Property_Name_text__c from Domain_Review__c Where Exchange_Quality_ID__c =: a0W56000002PgXfEAK];

for(domain_review__c a: PR)
{
    for(Domain_review__c b: newPR)
    {
        if(a.Property_Name_text__c == b.property_text__c)
        {
            // 每次匹配时新建对象实例
            Domain_review__C PRrecordupdate = new Domain_review__C();  
            PRrecordupdate.Id = a.Id;
            PRrecordupdate.Approval_Status__c = b.Approval_Status__c;
            PRrecordupdate.Rejection_Reason__c = b.Rejection_Reason__c;
            PRrecordupdate.seller_name__c = b.seller_name__c;
            PRrecordupdate.Inventory_Relationship__c = b.Inventory_Relationship__c;
            
            PRCollectionupdate.add(PRrecordupdate);
        }
    }
}

PRmap.putall(PRCollectionupdate);

if(PRmap.size()>0){
    update PRmap.values();
}

额外优化建议

可以预先将newPR列表按property_text__c字段构建成Map,避免嵌套循环,提升执行效率(尤其是当数据量较大时):

// 预先构建newPR的Map,key为property_text__c,value为对应的记录
Map<String, Domain_review__C> newPRMap = new Map<String, Domain_review__C>();
for(Domain_review__c b : newPR) {
    newPRMap.put(b.property_text__c, b);
}

for(domain_review__c a: PR)
{
    Domain_review__C b = newPRMap.get(a.Property_Name_text__c);
    if(b != null) {
        Domain_review__C PRrecordupdate = new Domain_review__C();  
        PRrecordupdate.Id = a.Id;
        PRrecordupdate.Approval_Status__c = b.Approval_Status__c;
        PRrecordupdate.Rejection_Reason__c = b.Rejection_Reason__c;
        PRrecordupdate.seller_name__c = b.seller_name__c;
        PRrecordupdate.Inventory_Relationship__c = b.Inventory_Relationship__c;
        
        PRCollectionupdate.add(PRrecordupdate);
    }
}

内容的提问来源于stack exchange,提问作者Yami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 03:25:13