+ Start a Discussion
HaroldHarold 

Lookup relationships and dynamic soql

So I have a basic query Select id, Object__r.Name from myCustomObject  that works fine to get me the name field from my lookup relationship object__r

 

However, when I build this statement exactly the same and run it through database.query(mySql); I get an invalid field name on the object__r.Name?

 

Are there issues using __r relationship with dynamic soql?

HaroldHarold

Actually I've discovered that it's not the query that fails. It happens while trying to retrieve the value from the actual returned object.  Example:

String sField = 'Field__r.Name';

List<sObject> l = Database.Query('Select id,' + sField + 'from CustomObject limit 1');

 

String sValue = l[0].get(sField);  //this would fail with an invalid field name.  

 

Here is the fix if anyone is interested

 

String sField = 'Field__r.Name';

List<sObject> l = Database.Query('Select id,' + sField + 'from CustomObject limit 1');

 

String sFieldSub1 = sField.SubString(0,sField.indexof("."));

String sFieldSub2 = sField.SubString(sField.indexof(".") + 1,sField.Length()); //though I imagine you could use a spilt string also.

String sValue = l[0].getObject(sFieldSub1).get(sFieldSub2);