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
si402si402 

Referenced Fields in SOQL Queries

I am trying to write a fairly straightforward SOQL query, which is not working how i'd expect. 

 

// Substituting valid where criteria for etc...

sObject Temp = Database.query('SELECT Contact.Account.Name FROM Contacts WHERE etc.');

System.Debug(Temp.get('contact.account.name'));

 

I get an 'Invalid field 'contact.account.name'' error whenever i try this.

 

I've tried these variations and all of their various capitalizations (not that it should matter)

Temp.get('name')

Temp.get('account.name')

 

Obviously, this works:

 

Contact Temp = [SELECT Contact.Account.Name FROM Contacts WHERE etc.'];

System.Debug(Temp.Account.Name);

 

But I need to be able to build the query string dynamically, querying against arbitrary salesforce objects. I feel like i'm just missing something simple, but I've been over the documentation numerous times with no luck.

 

Any assistance anyone could offer would be greatly appreciated.

 

Thanks,

 

Mark

 

 

 

 

incuGuSincuGuS

Hi Mark,

 

If you want to build dynamic Queries you gotta do it this way:

 

String q = 'SELECT Id FROM Whatever';
sObject[] parentWithRespie = Database.Query(q);

 

If you want to retrieve child records from a parent you need to use getSObject

The getSObject method is for retrieving fields from a parent.

 

res[0].getSObjects('RelationshipObject__r');

 

Also found this :

 

 

 

Setting and Retrieving Foreign Keys


To set or retrieve the record associated with a foreign key, use the getSObject and putSObject

methods. Note that these methods must be used with the sObject data type, not Object. For example:

 

<script type="text/javascript">// swfobject.registerObject("clippy.d3465e141", "9"); // </script>
 SObject c = 
Database.query('SELECT Id, FirstName, AccountId, Account.Name FROM Contact LIMIT 1');
SObject a = c.getSObject('Account');

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_dml.htm

 

Hope this helps, it seems its done the same way either way around.

 

Gaston.

 

Richie DRichie D

Hi,

 

Not sure your query is correct - do you have an extra 's' on contact?

 

Perhaps

 

 

sObject Temp = Database.query('SELECT Account.Name FROM Contact WHERE etc.');

 will work ok??

R.