Adam Thornton
Adam Thornton

Reputation: 172

Initialise object in apex with related data

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?

Upvotes: 0

Views: 5287

Answers (1)

mast0r
mast0r

Reputation: 820

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;

Upvotes: 1

Related Questions