[SalesForce] Querying custom field on User using createdBy

I want to extract a custom field value in a soql using createdby reference.

List<CaseComment> cc = [Select createdby.customField__c from caseComment];

The soql is failing to recognize the customField.
Is this not allowed?

Best Answer

The audit fields that refer to the user object are of the Name data type; this data type represents a few standard fields you can get data from, because these fields can actually refer to things other than just users. For example, CaseComment records can be created by a Contact record (by virtue of the Self Service Portal or Community portals).

What this means is that you can only access a handful of certain standard fields designed to work with the Name data type. If you want custom data, you'll need to use TYPEOF, which is still a developer preview feature, or you'll need a separate query, in the usual fashion:

Map<Id, User> users = new Map<Id, User>();
CaseComment[] comments = [SELECT CreatedById FROM CaseComment];
for(CaseComment record: comments) {
  users.put(record.CreatedById, null);
}
users.putAll([SELECT CustomField__c FROM User WHERE Id = :users.keySet()]);
User commentUser;
for(CaseComment record: comments) {
  if((commentUser = users.get(record.CreatedById)) != null) {
    // Do something with commentUser
  }
}