I found myself building a custom feed item list that required displaying the user's profile image from the Chatter feed. This seemed like an easy task because normally you can get the profile image by querying on a User lookup. But of course sometimes the things that you think will be easy turn out to be much more complicated.
My first attempts looked like this. First trying to access it from the Parent
field:
feedItemsList = [ | |
SELECT Id, Body, Title, CreatedDate, Parent.Name, Parent.MediumPhotoUrl | |
FROM FeedItem | |
WHERE CreatedDate = LAST_N_DAYS:30 | |
ORDER BY CreatedDate DESC | |
]; | |
feedItemsList = [ | |
SELECT Id, Body, Title, CreatedDate, Parent.Name, Parent__r.MediumPhotoUrl | |
FROM FeedItem | |
WHERE CreatedDate = LAST_N_DAYS:30 | |
ORDER BY CreatedDate DESC | |
]; | |
feedItemsList = [ | |
SELECT Id, Body, Title, CreatedDate, Parent.Name, Parent.Photo.mediumPhotoUrl | |
FROM FeedItem | |
WHERE CreatedDate = LAST_N_DAYS:30 | |
ORDER BY CreatedDate DESC | |
]; |
Next trying to access it from InsertedBy
lookup:
feedItemsList = [ | |
SELECT Id, Body, Title, CreatedDate, Parent.Name, InsertedBy.MediumPhotoUrl | |
FROM FeedItem | |
WHERE CreatedDate = LAST_N_DAYS:30 | |
ORDER BY CreatedDate DESC | |
]; | |
feedItemsList = [ | |
SELECT Id, Body, Title, CreatedDate, Parent.Name, InsertedBy__r.MediumPhotoUrl | |
FROM FeedItem | |
WHERE CreatedDate = LAST_N_DAYS:30 | |
ORDER BY CreatedDate DESC | |
]; |
All of these fail with an error saying that it "Didn't understand relationship" to the image. :thinking:
Polymorphic Fields
What I learned is that FeedItem could contain polymorphic fields which means that it could potentially be one of several different types of objects and we would need to handle the SOQL query differently based on the object we wanted to reference.
As of API version 46.0, you can use the TYPEOF
expression in SOQL to control which field type you want to query in a polymorphic relationship. After reviewing using TYPEOF, I updated my query to only lookup the user profile image when InsertedBy
is type User
like this:
feedItemsList = [ | |
SELECT Id, Body, Title, Parent.Name, CreatedDate, | |
TYPEOF InsertedBy WHEN User THEN Name, MediumPhotoUrl END | |
FROM FeedItem | |
WHERE CreatedDate = LAST_N_DAYS:30 | |
ORDER BY CreatedDate DESC | |
]; |
And it worked! Now I finally have a list of feed items that include the user's profile image. Hopefully that will help someone else who's running into the same issue. :thumbsup: