如何从 SOQL 查询中提取 Parent.Parent 字段值?

How to extract Parent.Parent field value from SOQL Query?

这是我的查询

SOBject acc = [Select Id, Name, (Select Id, Account.Parent.Parent.Name, Name from Contacts__r) from Sales_Location__c where Id ='a005j000009xxxBAxU'];
Contact abc =(Contact)(acc.getSobjects('Contacts__r')).get(0);
System.debug(abc.get('Account.Parent.Parent.Name'));

但是如果我直接使用 abc.Account.Parent.Parent.Name 而不是使用 get(),我会得到结果。但是我不知道为什么我的代码在 get() 的情况下会失败。在实际场景中 abc 是 SObject 类型,这就是我需要在这里使用 get() 的原因。

sObject.get() 仅适用于 1 个字段,不会通过“点”行进。见https://salesforce.stackexchange.com/a/24804/799(不要脸的外挂,是我自己的回答)

你可以试试

Sales_Location__c location = [Select Id, Name, 
    (Select Id, Account.Parent.Parent.Name, Name from Contacts__r)
    from Sales_Location__c 
    where Id ='a005j000009xxxBAxU'];

if(!location.Contacts__r.isEmpty()){
    Contact abc = location.Contacts__r[0];
    if(abc.Account != null && abc.Account.Parent != null && abc.Account.Parent.Parent != null){
        System.debug(abc.Account.Parent.Parent.Name);
    } else {
        System.debug('there is no grandparent account');
    }
}

但是这种空值检查在一段时间后变得非常烦人。最近添加了一个 https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SafeNavigationOperator.htm

// the query is stupid, the parent name will always be null
// but my point is it's accessed safely, it won't throw the
// null reference exception
Contact c = [SELECT Account.Parent.Name 
    FROM Contact 
    WHERE Account.ParentId = null
    LIMIT 1];
System.debug(c.Account?.Parent?.Name);

P.S。即使你的函数接收到一个通用的 sObject - 你总是可以尝试将它转换回原来的

Sales_Location__c loc = (Sales_Location__c) abc;

所以它稍后会为您提供更简单的代码,compile-time 检查...如果不需要,请不要使用通用对象。如果您的函数可以接受来自多个来源的对象,也请检查 instanceof