+ Start a Discussion
Adam CadamAdam Cadam 

SOQL query with IN clause and a List

How do you create a SOQL query using a filed name from a List of custom objects. I tried this but it doesn't work:
 
List<Payment__c> payments = [SELECT Id,Name,Order__c,Settled_Date__c,Success_Date__c FROM Payment__c WHERE Order__c IN :orders.customerOrderCode];

'orders' is a List<CustomApexObject> where CustomApexObject is just what it says, and it has a field called customerOrderCode, which contains a valid 'Order' Id,

The code above fails because customerOrderCode is a field on the CustomApexObject, not on the List<CustomApexObject>

Thanks!
Best Answer chosen by Adam Cadam
ApuroopApuroop
Maybe this should do the job. Adjust the spellings of the objects.
 
List<Orders> myCustomObjectList = [SELECT Id FROM Orders]; //Get your list using a better query.
List<String> myStringList = new List<String>();

for(Order o : myCustomObjectList){
    myStringList.add(o.customOrderCode); //Hopefully this field is a text field?!
}

List<Payment__c> payments = [SELECT Id,Name,Order__c,Settled_Date__c,Success_Date__c FROM Payment__c WHERE Order__c IN :myStringList];

All Answers

ApuroopApuroop
Maybe this should do the job. Adjust the spellings of the objects.
 
List<Orders> myCustomObjectList = [SELECT Id FROM Orders]; //Get your list using a better query.
List<String> myStringList = new List<String>();

for(Order o : myCustomObjectList){
    myStringList.add(o.customOrderCode); //Hopefully this field is a text field?!
}

List<Payment__c> payments = [SELECT Id,Name,Order__c,Settled_Date__c,Success_Date__c FROM Payment__c WHERE Order__c IN :myStringList];
This was selected as the best answer
Adam CadamAdam Cadam
Perfect - that's just what I needed.
Oh for C# with LINQ and Lamdas!