Search code examples
listapex-codecustom-fieldssoql

SOQL - APEX - List


Hello Folks,
I have a list which has values from a query. The list has multiple fields, how can I access a specific field from this list?

Problem:

List <Account> listS = [Select 
                         (Select S__c from AS__r 
                         where S__r.Abc__c = 'Confirmed'), 
                         (Select PQR__c from AHS__r) 
                       from Account where Id in: TravellerIds];

List <AS__c> listAS = new list <AS__c>();
for (Account t: listS){
    listAS.add(t.AS__r);
}

Problem in pseudocode:
For (every Account in listS) {
ListAS.add(S__c field from the listS); }

I have tried what I mentioned in the Problem section but I am unable to access it. Please help me.

Error that I get is this : List has more than 1 row for assignment to SObject.

Thanks a lot for the help.

Note: I do not want to access the S_c field inside the for loop for every AS_c.. I want to access it for every Account.


Solution

  • As you're querying a parent child relationship the field t.AS__r on the Account object is actually a list of the objects that meet the sub query criteria. Therefore all you need to do is change listAS.add(t.AS__r); to be listAS.addAll(t.AS__r); and this will make your example code work - adding all of the items returned in the sub query to your new list.

    By extension if you wanted to add all the S_c fields, as you say in your pseudo code, then all you need to do is loop through the sub query list for each account and add the S_c field to a list like so:

    List<string> listOfS = new List<string>();
    for(Account acc : listAS){
      for(A__c a: acc.AS__r){
         listOfS.add(a.S__c);
      }
    }
    

    This presumes that your custom object referred to by the relationship name AS__r has an API name of A__c and that the field S__c is of type string - but hopefully you get the idea.

    Does this help?