Search code examples
parse-platformmany-to-manyrest

Fetch many-to-many relation items with REST API


In Parse I've two classes with a many-to-many relation, for example Products and its ProductImages. I've created in the class Products a relation with ProductImages and all work fine with querying and updating. There is limited documentation on many-to-many relation on Parse.

How to query all the Products with respective ProductImages data (Rest API Call) ?

Expected Response will be like this:

{
"name": "Apples",
"productImages": [
  {
"imagePath":"",
"videoPath":""
  }, {
"imagePath":"",
"videoPath":""
  }
]
}

Solution

  • There is no endpoint in the REST api to query both classes at the same time, but you can write a cloud code function to do that and retrieve all the data that you need with a single request. I'd do something like this:

    Parse.Cloud.define('getProductsAndImages', async req => {
      const productsQuery = new Parse.Query('Product');
      const products = await productsQuery.find();
      return Promise.all(products.map(async product => ({
        ...product.toJSON(),
        productImagesObjs: await product.get('productImages').query().find()
      })));
    });
    

    Then you can call the function using the REST API like this:

    curl -X POST \
      -H "X-Parse-Application-Id: ${APPLICATION_ID}" \
      -H "X-Parse-REST-API-Key: ${REST_API_KEY}" \
      -H "Content-Type: application/json" \
      -d '{}' \
      https://server.address.com/parse/functions/getProductsAndImages