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
Allan Pincus - AdminAllan Pincus - Admin 

access custom field in user via owner relationship

I am not new to SQL, but I am new to SOQL.  I have a custom field in the user object that I cannot reach with owner.<custom field>

I've been researching how to do this, and I still have yet to figure out a solution.  Is there no way for me to access it in a query?  

An example query I need to work is this:

SELECT id, name, owern.name, owner.<custom field> FROM lead WHERE id = <my value>

Can anyone tell me the correct syntax, or confirm it is "impossible" with SOQL?  Is there an alternative using SOSL if so?



 
SarvaniSarvani
Hi Allan,

You cannot query on the custom fields of user object from other sobject records like you did. It throws error and its expected. Only few fields on the user object can be queried directly using owner.fieldname notation. Please refer to the link https://skaruz.com/salesforce-how-to-access-owner-custom-fields-in-a-soql-query/ fields which can be refered so. As discussed in the link if you want the custom field value you can create a formula field on lead object with default value of Owner:User.Custom_field__c     OR

If you do not want to create field but see the value stored you can use below code in your Anonymus window which will fetch the values.

To execute below code -> On top right gear icon-> Find Developer console -> When the window opens -> Choose Debug (Third Option in Menu bar) -> Select Open Execute Anonymus window -> Paste the below code -> Before clicking Execute on the window select open log checkbox and click execute.
This will open a new window with results with execution log as default window. Select debug only checkbox in the bottom panel. You can see only the record you are looking for.
lead leadrecord =[select id,ownerid, owner.name from lead where id ='Your lead Id'];
User Userlist=[select id, Account_type__c from user where Id=:leadrecord.ownerid];
System.debug(Userlist);

Hope this helps! Please mark as best if it does.

Thanks
Allan Pincus - AdminAllan Pincus - Admin
Unfortunately, we do not have access to the developer console.  We use Workbench to access the SF database.  Is there a way I can try it that way?
SarvaniSarvani
Hi Allan,

You can execute the code in workbench by navigating to Utilties -> Apex Execute and paste your code. You can see the user id and the custom field. If you are not able to see the field which means you do not have access to the field.

Thanks,
Sarvani
Allan Pincus - AdminAllan Pincus - Admin
Thanks!  I do have access to the field.  I can access it directly:  SELECT <custom field> FROM user
THe issue is indirectly accessing it so I can include it as part of another query, which I cannot do using owner.<custom field>.
I will try Apex.