Search code examples
javascriptgoogle-app-maker

Q. How to query a model, in a one-to-many relationship, return associated records?


Models:

  • Purchase Orders
  • Items

Relationship: Purchase Orders (one) <--> (many) Items

Ownership: Purchase Orders (Owner) -> Items

I am able to return all records from Items model using this code:

//Query Items and return records related to each Purchase Order.
  var query = app.models.Items.newQuery();
  var allItems = query.run();

But how do I return only the items associated with each purchase order record?


Solution

  • You'll need to pass the purchase order record key to your query and filter items by it. For example:

      function getPurchaseOrderItems(purchaseOrderRecordKey){
          //Query Items and return records related to each Purchase Order.
          var query = app.models.Items.newQuery();
          query.filters.PurchaseOrders._key._equals = purchaseOrderRecordKey;
          var allItems = query.run();
      }
    

    I recommend you to consult the official documentation for a more detailed explanation. That way you'll get a deeper and better understanding on how to work with relations.