It's All Writing.

Writing makes you happy.

How to retrive parent custom sobjects field value by SOQL at Apex

Environment

  • Apex
  • SOQL

Premise

Note that when retrieving parent SObject information with the child SObject's retriving query, it is necessary to receive the SOQL execution result in the SObject type.
For example, if you do the following, you can get only Opportunity Id and Name.

    List<Opportunity> objs = [
        SELECT
            Id,
            Name,
            AccountId,
            Account.Name,
            SomeCustom__r.Id,
            SomeCustom__r.Name
        FROM
            Opportunity
    ];
    System.debug(objs);
    // returns only Opportynity.Id and Opportunity.Name

Code

gist.github.com

To retrive the parent SObject data, if you know the relationship name (e.g. Account, SomeCustom__r) , just pass the relationship name to the getSObject method.
If you know only the SObject API reference name and do not know the relationship name, you can get the Schema.SObjectField value using Schema.SObject and pass this Schema.SObjectFIeld to getSObject.

The method using Schema is recommended, although the code is a little longer because data can be obtained in the same way with standard SObject and custom SObject.

Reference

developer.salesforce.com