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
Arindam MukherjeeArindam Mukherjee 

How to get lookup columns from SQQL

I am new to Apex world. I am using following code:

Qstr = "Select CreatedBy.username FROM Opportunity Where Id = '006i000000M7NP7AAN'";

SObject[] usrObj  = database.query(Qstr);
if (usrObj.size() > 0)
{
        retVal = (String)usrObj[0].get('CreatedBy.username');
}

get operation on usrObj[0] is failing with following error:

Invalid field CreatedBy.username for Opportunity     

Any idea?

Thanks in advance,
Arindam
Madhan Raja MMadhan Raja M
Hi Arindam,

Try the below code:

String retVal;
Opportunity opp = [Select CreatedBy.username FROM Opportunity Where Id = '006i000000M7NP7AAN'];
retVal=opp.CreatedBy.username;

Regards,
Madhan Raja M
Arindam MukherjeeArindam Mukherjee
Hi Madhan,

  I am building the query dynamically from metadata. So, I am using Database.Query to run the dynamic string and extract the result dynamically using get API.  I don't think that I can use dynamic string in your approach.

Thanks,
Arindam
Madhan Raja MMadhan Raja M
Hi Arindam,

You cannot use "CreatedBy.username" in retVal = (String)usrObj[0].get('CreatedBy.username'); because the usrObj does not contain the "CreatedBy.username" column.

The usrObj has the below information

(Opportunity:{CreatedById=XXXXXXXXXXXXXXXXXX, Id=006i000000M7NP7AAN}

you can use retVal = (String)usrObj[0].get('CreatedById'); to get the created user ID and then have one more query to get the username from User object.

Regards,
Madhan Raja M

kevin lamkevin lam
You don't need to use a generic sObject:

List<Opportunity> usrObj  = database.query(Qstr);
if (usrObj.size() > 0)
{
        retVal = usrObj[0].CreatedBy.username;
}