function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
bperry8086bperry8086 

Turning an ID into an object?

Is there a way to cast or convert a Salesforce object ID into into an object?

 

I'm doing a SOQL query that gives me a list of child objects.  Included in that list is an ID for a parent object (parent is a lookup field).  I need the parent object.  What's the best way to get this?

 

I could have put another SOQL query within my original for loop, but I realize that's not recommended due to the limit on SOQL queries.

Best Answer chosen by Admin (Salesforce Developers) 
Jerun JoseJerun Jose
You can.

Suppose you are doing an SOQL like this
[select id, AccountID from Contact]

you can then create a new account object as:
Account acc = new Account(ID = con.AccountID);

and then do
acc.F1__c = 'has contact';
update acc;

I'm guessing that thats where you are headed.

All Answers

kerwinkerwin

I'm not sure if i understand your post correctly.. but you could mention the parent object in the SOQL query rather than the ID field itself. e.g.:

 

instead of

[select Name, parent_Object__c from Child_Object__c]

use

[select Name, parent_Object__r.Name from Child_Object__c]

 

in which case you could access Child_Object__c.parent_Object__r.Name.

Jerun JoseJerun Jose
You can.

Suppose you are doing an SOQL like this
[select id, AccountID from Contact]

you can then create a new account object as:
Account acc = new Account(ID = con.AccountID);

and then do
acc.F1__c = 'has contact';
update acc;

I'm guessing that thats where you are headed.
This was selected as the best answer
bperry8086bperry8086

Looks like this does what I want.  For the benefit of other readers, it appears that creating the object as you describe via the constructor:

 

Account acc = new Account(ID = con.AccountID);

 

fills in just the ID field on the object.  Any other desired fields must also be transferred.  I'd had hopes that creating the object via the constructor would automatically fill in the other fields.  That's a detail, the major issue of how to turn an ID into an object is solved.

bperry8086bperry8086

Thanks for the response.  There may indeed be a better way to get a what I want with a SOQL query.  The relationships in my db make my head hurt sometimes(several are IDs rather than descriptive strings), so I try to keep the queries simple.  I'm better at debugging code than SOQL queries.  The approach Jerun outlines below appears to do what I need.