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
Timmy AhluwaliaTimmy Ahluwalia 

Custom Object to USER object SOQL

Hi,
my custom object has a lookup with USer object-- createdBY
i am trying to fetch the data from custom object as
createdby.name but the field is not fetching, please help with this.
Thanks
Best Answer chosen by Timmy Ahluwalia
Khan AnasKhan Anas (Salesforce Developers) 
Hi Timmy,

Greetings to you!

SOQL Query to Get the CreatedBy and LastModifiedBy User Name:
SELECT Id, Name, CreatedBy.FirstName, CreatedBy.LastName, CreatedBy.Name, LastModifiedBy.FirstName, LastModifiedBy.LastName, LastModifiedBy.Name FROM Object__c

Id = CreatedById
Name = CreatedBy.Name

If you are using a debug statement to view the output, then you will only see the Ids, however, you will be able to reference the actual names. Try like this:
List<Object__c> obj = [SELECT Id, CreatedBy.Name, LastModifiedBy.Name FROM Object__c];
for(Object__c o : obj){
	System.debug('Created By ->  ' + o.CreatedBy.Name);
	System.debug('Last Modified By ->  ' + o.LastModifiedBy.Name);
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas

All Answers

Jessica RiffeJessica Riffe
Can you post your code please?
Khan AnasKhan Anas (Salesforce Developers) 
Hi Timmy,

Greetings to you!

SOQL Query to Get the CreatedBy and LastModifiedBy User Name:
SELECT Id, Name, CreatedBy.FirstName, CreatedBy.LastName, CreatedBy.Name, LastModifiedBy.FirstName, LastModifiedBy.LastName, LastModifiedBy.Name FROM Object__c

Id = CreatedById
Name = CreatedBy.Name

If you are using a debug statement to view the output, then you will only see the Ids, however, you will be able to reference the actual names. Try like this:
List<Object__c> obj = [SELECT Id, CreatedBy.Name, LastModifiedBy.Name FROM Object__c];
for(Object__c o : obj){
	System.debug('Created By ->  ' + o.CreatedBy.Name);
	System.debug('Last Modified By ->  ' + o.LastModifiedBy.Name);
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
This was selected as the best answer