【问题标题】:Accessing parent object fields in trigger handler class访问触发器处理程序类中的父对象字段
【发布时间】:2017-03-23 14:55:20
【问题描述】:

我正在为对象“A”的插入后触发器编写触发器处理程序类。将 trigger.new 传递给处理程序类中的函数后,我可以访问 A 的字段,但其父对象字段均为空。如何在不将触发器本身的 Id 与 trigger.new 变量一起传递的情况下访问父对象字段。

这里是示例触发器::

if(trigger.isInsert && Trigger.isAfter){


      TriggerHandler.handleAfterInsert(trigger.new);

}  

这里是处理程序类::

  public class DedupeTriggerHandler{
    public static void handleAfterInsert(List<A__c >AList) {
    // accessing parent objects field here

           }
    }

【问题讨论】:

    标签: triggers salesforce apex


    【解决方案1】:

    这样的东西会起作用吗?我在我的类中做类似的事情来访问子对象记录。您基本上需要获取 A__c 的所有 Id 的集合,然后执行 SOQL 查询以查看与 A__c 关联的子对象记录。下面,我使用“Contact”作为示例子对象。

    public static void handleAfterInsert(List<A__c> AList) {
        Set<Id> aIds = new Set<Id>(); //set for holding the Ids in AList ("trigger.new")
    
        // 1. Get a list of all A__c Id's in the trigger
        for (A__c ac : AList) {
            // Add the Id to set
            aIds.add(ac.Id);
            System.Debug('^^^^^## A__c Id added to list: ' + ac.Id);
        }
    
        // 2. Loop through all A__c affected by trigger (using one SOQL query)
        for (A__c ac : [SELECT Id, (SELECT Id, OwnerId FROM Contacts) FROM A__c WHERE Id in :aIds]) {
            // You should now be able to see child table data here:
            for (Contact c : ac.Contacts) {
                ...
                ...
            }
            ...
            ...
        }
    }
    

    【讨论】:

    • 我想访问父对象字段而不是子对象字段。您可以使用内部soql查询访问子对象字段。通常我们可以使用'.'(点)运算符访问父对象字段.但在这种情况下它不起作用!
    • 我可能仍然存在误解,但在这种情况下(根据我的经验),您只需要构建父 ID 的映射。因此,如果您正在处理联系人并想要获取 Account sObject 字段,您只需遍历 trigger.new 以获取 AccountId 并将其添加到地图中。然后你可以做一个 SOQL 来获取你需要的 Account 字段(即[Select ID, Name, Owner from Account where ID in : AccountIDs])。问题是,对于 trigger.new、trigger.oldmap 等,我不认为在您从数据库执行 SOQL 之前,您无法直接访问 Parent 或 Child sObject。
    • 是的,''使用 trigger.new、trigger.oldmap 在从数据库执行 SOQL 之前,您无法直接访问 Parent 或 Child sObjects''。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    相关资源
    最近更新 更多