0

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?

Trevor
  • 13,085
  • 13
  • 76
  • 99
Adam Thornton
  • 172
  • 2
  • 9

1 Answers1

1

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;
Community
  • 1
  • 1
mast0r
  • 820
  • 5
  • 13
  • 1
    How do you do this with a custom object? If I use opp.Account__c it returns an Id, and if I use opp.Account__r it expects a field. Edit: It seems you can do it using the __r field. – Adam Thornton Oct 01 '12 at 14:35
  • Thanks, I will mark this as answered in a minute but your first statement isnt quite right, you only have to define the fields you want to use in the SOQL query. – Adam Thornton Oct 01 '12 at 14:49
  • Right, just a tradition from my practice :) Edited now – mast0r Oct 01 '12 at 14:59