Understanding—No such column on entity 'Name' error!
One can get errors like:
No such column ‘SmallPhotoUrl’ on entity ‘Name’ OR No such ‘column CompanyName’ on entity ‘Name’.
On an SOQL statement like:
SELECT CreatedBy.CompanyName, FeedPost.Body, Id, CreatedBy.Name FROM AccountFeed.
SELECT CreatedBy.SmallPhotoUrl, FeedPost.Body, Id, CreatedBy.Name FROM AccountFeed.
SELECT Id, FeedPost.CreatedBy.SmallPhotoUrl, (SELECT Id, CreatedBy.Name, CreatedBy.SmallPhotoUrl, CommentBody FROM FeedComments) FROM NewsFeed
The column responsible for this error is boldly highlighted in the above SOQL statements. The error is so confusing; you must be wondering, “I queried on User(CreatedBy) relation, then why is the field expected to be there on the entity ‘Name’?
Why is this error thrown for entity “Name”?
It is because “CreatedBy” and many other Salesforce relations become “polymorphic” if pointing to more than one type of object as a parent. This is what the Salesforce “Relationship Queries” doc says:
“A polymorphic key is an ID that can refer to more than one type of object as a parent. For example, either a contact or a lead may be the parent of a task. In other words, the whole field of a task may contain the ID of either a contact or a lead. If an object can have more than one type of object as a parent, the polymorphic key points to a Name object instead of a single object type.”
So, one can’t expect a single SObject type field for polymorphic relations/keys. Rather, check what fields are available in the entity “Name”. That is why one can’t find User sobject’s fields like SmallPhotoURL and CompanyName on CreatedBy polymorphic relationships.
Note: Not all CreatedBy relationships are polymorphic; it totally varies from sobject to sobject.
How to know if a relationship is polyamorous?
To know whether a relation is polymorphic, you can do either of the following:
User describeSObjects call, as described in the section “Understanding Polymorphic Keys and Relationships” of the Salesforce “Relationship Queries” doc.
Use Eclipse > Schema Browser and expand into the “relationship column > Type Data > Reference To,” as shown below: