I see that there is a related list on Orders showing the OrderItems but there is not field on orders that I can SOQL query in Apex.


You need to look into relationships. OrderItems will not show as a field on the Order Object, as they are a related object. Take a look at some of the documentation on relationships



In general, you need to query the parent Object and include a sub query for the child records.

List<Parent_Object__c> parentList= [Select Id, Name, Field1__c, Fieldx__c (Select Id, Name, Field1__c, Fieldx__c From Child_Objects__r) From Parent_Object__c];

You can then check this query in Apex Anon

for(Parent_Object__c par : parentList) {
     system.debug('Parent Object: ' + par);
     system.debug('Children: ' + par.Child_Objects__r);

@sfdc_ninja is right. Just adding that, specifically, for the Order object you have two different ways to get the OrderItems for an Order.

A. Get as a related list by querying the Order object.

Id orderId = //somehow get this.
List<Order> orders = [
    SELECT Id, Status,
          (SELECT Id, UnitPrice, Quantity, OrderId FROM OrderItems)
    FROM Order
    WHERE Id = :orderId
if (orders.isEmpty()) {
   // likely an error if no Order returned...handle this somehow
Order o = orders.get(0);
List<OrderItem> orderItems = o.OrderItems;

B. Query the OrderItem object directly, using the OrderId field:

Id orderId = //somehow get this.
List<OrderItem> orderItems = [
    SELECT Id, UnitPrice, Quantity, OrderId,
    FROM OrderItem
    WHERE OrderId = :orderId

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.