function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
DJPDJP 

New to Apex and was looking for a class that would return Opp header and Opp line items where Opp created Date or Modified date is equal to Date I pass.

Hello, I m very new to Apex programming and was looking for the best way to write an APEX class that will give me Opportunity Header Data and its related Products (line item on that Opportunity) where the created and modified date is the date I pass to this class. I know how to write this SQL but wanted to know how to get this in Apex Class. 

Thanks 
DJ
Best Answer chosen by DJP
Aslam ChaudharyAslam Chaudhary
String queryString = 'SELECT Id, Name,Description , ' + 
           '(SELECT Id, Quantity FROM OpportunityLineItems LIMIT 1) FROM Opportunity  ';
SObject[] queryParentObject = Database.query(queryString);
         
for (SObject parentRecord : queryParentObject){ 
    Object ParentFieldValue = parentRecord.get('Name'); 
    // Prevent a null relationship from being accessed
    SObject[] childRecordsFromParent = parentRecord.getSObjects('OpportunityLineItems');
    if (childRecordsFromParent != null) {
        for (SObject childRecord : childRecordsFromParent){ 
            Object ChildFieldValue1 = childRecord.get('Id'); 
            Object ChildFieldValue2 = childRecord.get('Quantity'); 
            System.debug('Parent Filed Name: ' + ParentFieldValue + 
            '. Line Fields: '+ ChildFieldValue1 + ' ' + ChildFieldValue2);
        }
    }              
}
I have used Dynamic SOQL. You can use same query in normal SOQL.
 

All Answers

Aslam ChaudharyAslam Chaudhary
String queryString = 'SELECT Id, Name,Description , ' + 
           '(SELECT Id, Quantity FROM OpportunityLineItems LIMIT 1) FROM Opportunity  ';
SObject[] queryParentObject = Database.query(queryString);
         
for (SObject parentRecord : queryParentObject){ 
    Object ParentFieldValue = parentRecord.get('Name'); 
    // Prevent a null relationship from being accessed
    SObject[] childRecordsFromParent = parentRecord.getSObjects('OpportunityLineItems');
    if (childRecordsFromParent != null) {
        for (SObject childRecord : childRecordsFromParent){ 
            Object ChildFieldValue1 = childRecord.get('Id'); 
            Object ChildFieldValue2 = childRecord.get('Quantity'); 
            System.debug('Parent Filed Name: ' + ParentFieldValue + 
            '. Line Fields: '+ ChildFieldValue1 + ' ' + ChildFieldValue2);
        }
    }              
}
I have used Dynamic SOQL. You can use same query in normal SOQL.
 
This was selected as the best answer
DJPDJP
Thank you Aslam. This has helped me clarify few things 
Aslam ChaudharyAslam Chaudhary
Please close this thread and Mark as best answer if you feel.