0
votes

I require a separate object which contains the related fields of a child object.

Currently I do it like this:

Opportunity opp = [SELECT Id, Name, Account.Id, Account.Name FROM Opportunity LIMIT 1];

Account acc = new Account(
    Id        = opp.Account.Id,
    Name      = opp.Account.Name
);

When working with a large related object I have to initialise many more fields than this and the script becomes very large and ugly.

What is the quickest way to initialise the related field data into a separate object?

1

1 Answers

1
votes

You must define the all fields in your SOQL query (mor info here).

But it is not necessary if you want to clone the object:

Opportunity opp = [SELECT Account.Id, Account.Name 
                   FROM Opportunity 
                   LIMIT 1];

Account acc = opp.Account;

Example with Custom Object:

Contract__c c = [ Select Account__r.FirstName 
                  From Contract__c 
                  Where Account__r.FirstName != null 
                  Limit 1];

Account a = c.Account__r;