+ Start a Discussion
Hari N 20Hari N 20 

IN operator must be used with an iterable expression

Hi All,
I am getting error as following : IN operator must be used with an iterable expression .
My code is : 
List<Task> ts1=[Select Id,WhoId from Task];
    for(Task ts2 : ts1){
    Map<ID, Obj1__c> mapAccounts = new Map<ID, Obj1__c>([SELECT Id, Name, Filed1__c  FROM Obj1__c WHERE                                                                                                               Field1__r.Id IN: ts2.whoId]);
}
Filed1__c is lookup to account.
How to resolve this?

Thanks in Advance
Best Answer chosen by Hari N 20
Lalit Mistry 21Lalit Mistry 21
Try below code Hari,
 
List<Task> ts1=[Select Id,WhoId from Task];
Set<Id> whoIds = new Set<Id>();
    for(Task ts2 : ts1){
		whoIds.add(ts2.WhoId);
    
}
Map<ID, Obj1__c> mapAccounts = new Map<ID, Obj1__c>([SELECT Id, Name, Filed1__c  FROM Obj1__c WHERE Field1__r.Id IN: :whoIds]);

 

All Answers

Lalit Mistry 21Lalit Mistry 21
Hi Hari,

Use below SOQL query instead
[SELECT Id, Name, Filed1__c  FROM Obj1__c WHERE  Field1__r.Id = :ts2.whoId]
Hari N 20Hari N 20
Hi,
Thank you for your reply.
Its working.
Now, when I am inserting recording in custom object I am getting this error :  System.LimitException: Too many SOQL queries: 101​
Mohamed AzarudeenMohamed Azarudeen
Use SOQL Query in outside the for loop.
Lalit Mistry 21Lalit Mistry 21
Try below code Hari,
 
List<Task> ts1=[Select Id,WhoId from Task];
Set<Id> whoIds = new Set<Id>();
    for(Task ts2 : ts1){
		whoIds.add(ts2.WhoId);
    
}
Map<ID, Obj1__c> mapAccounts = new Map<ID, Obj1__c>([SELECT Id, Name, Filed1__c  FROM Obj1__c WHERE Field1__r.Id IN: :whoIds]);

 
This was selected as the best answer
Anupam Shrivastava 9Anupam Shrivastava 9
Hi Hari, Salesforce has some governor limits. Avoid using SOQL queries inside a loop.