SOQL - Querying for a list of users the current user is following

Ryan Elkins picture Ryan Elkins · Feb 7, 2012 · Viewed 14.9k times · Source

In my app I display a list of the current users. I request it like this:

Attempt 1

List<User> Following = [SELECT Id, Name, SmallPhotoUrl 
  FROM User 
  WHERE Id IN (
      SELECT ParentId 
      FROM EntitySubscription 
      WHERE SubscriberId = :UserInfo.getUserId()) 
    AND Id != :UserInfo.getUserId() 
  LIMIT 96];

This does exactly what it's supposed to when logged in as an admin but I found out that non-admins get an error:

Implementation restriction: EntitySubscription only allows security evaluation for non-admin users when LIMIT is specified and at most 1000

OK, no big deal, I'll just slap a LIMIT on there like so:

Attempt 2

List<User> Following = [SELECT Id, Name, SmallPhotoUrl 
  FROM User 
  WHERE Id IN (
      SELECT ParentId 
      FROM EntitySubscription 
      WHERE SubscriberId = :UserInfo.getUserId() 
      LIMIT 1000) 
    AND Id != :UserInfo.getUserId() 
  LIMIT 96];

Easy, right? WRONG. This gives the following:

expecting a right parentheses, found 'LIMIT'

OK...

I then tried breaking it out like so:

Attempt 3

List<EntitySubscription> sub = [SELECT ParentId 
  FROM EntitySubscription 
  WHERE SubscriberId = :UserInfo.getUserId() 
  LIMIT 1000];
List<Id> ids = new List<Id>();
for(EntitySubscription s : sub){
    ids.add(s.ParentId);
}
List<User> Following = [SELECT Id, Name, SmallPhotoUrl 
  FROM User 
  WHERE Id IN (:ids) 
    AND Id != :UserInfo.getUserId() 
  LIMIT 96]; 

I crossed my fingers and...

Invalid bind expression type of LIST<Id> for column of type Id

Hmm, I'd seen examples where this seemed to be possible, such as on the developerforce boards, so I'm at a bit of a loss now.

So here we are. I need to select a list of user names and pictures that a particular user is following on Chatter. If there is a completely different way to go about it I'm open to it.

Answer

Matt Lacey picture Matt Lacey · Feb 7, 2012

Try removing the parenthesis around the bind, i.e. change:

WHERE Id IN (:ids) 

to:

WHERE Id IN :ids

And also simplify the query by just making sure that your list of IDs doesn't contain the current user's ID:

List<EntitySubscription> sub = [SELECT ParentId 
  FROM EntitySubscription 
  WHERE SubscriberId = :UserInfo.getUserId() AND ParentId != :UserInfo.getUserId()
  LIMIT 1000];

Set<Id> ids = new Set<Id>();

for(EntitySubscription s : sub){
    ids.add(s.ParentId);
}

Hope that helps!