How to put sub query results into a List

To access that list of Copies try using the following:

BookList[0].Copies__r

You should see some data if that query returned something.

You can also try to run your query in the query editor in the Developer Console you might understand it better then.


This query of yours produces an outer list, with a child list on each one of those outer list items.

List<Book__c> BookList = [SELECT Id
                            , Name
                                (SELECT Id
                                    , Name
                                    , Status__c 
                                FROM Copies__r 
                                WHERE Status__c = 'Available') 
                            FROM Book__c];

Visually you could represent it like this:

Book__c
    List<Copy__c>
Book__c
    List<Copy__c>
Book__c
    List<Copy__c>

In order to access the Copies children of each Book in this structure, you're going to use the __r relationship to access each List<Copy__c>. (__r is a List of your subquery)

In a loop, they can be accessed like this:

for (Book__c book : BookList) {
    system.debug('Book: ' + book.Name);

    for (Copy__c copy : book.Copies__r) {

        // output both the book name and the copy name
        system.debug('Book: ' + book.Name + ' - Copy: ' + copy.Name);
    }
}

You could also write your query from the perspective of the Copy__c object, which would return a different structure.

List<Copy__c> CopiesList = [SELECT Id
                                    , Name
                                    , Status__c
                                    , Book__r.Id // from the parent Book__c
                                    , Book__r.Name // from the parent Book__c
                                FROM Copy__c
                                WHERE Status__c = 'Available'];

In a similar loop, they can be accessed like this:

for (Copy__c copy : CopiesList) {

    // output both the book name and the copy name
    system.debug('Book: ' + copy.Book__r.Name + ' - Copy: ' + copy.Name);
}

Tags:

Soql