简体   繁体   中英

How to create nested Many to Many relations in parse

I basically have 2 Parse classes in my Online Shop: Product and Order. While the user fills his shopping cart, I reflect that in a local array of items (javascript object) with a property for the product (parse class) and another property for the amount that particular product should have in the cart.

If I now save the order to parse (I'm using the self hosted open source version of parse-server), I end up with an order object like this:

{
  "_id": "8XK6gbZZvE",
  "items": [
    {
      "amount": 3,
      "product": {
        "__type": "Pointer",
        "className": "Product",
        "objectId": "VWOxzFui6R"
      }
    }
  ],
  "total": 1800,
  "status": "pending",
  ...
}

My problem with that is that I couldn't find a way to query for orders where the result already includes the products.

The only way I currently can think of is to get rid of the amount so that I don't have to nest the product class inside a JS object. And then just add a product multiple times to the array if necessary.

Something like that:

{
  "_id": "6j7l5acSB3",
  "items": [
    {
      "__type": "Pointer",
      "className": "Product",
      "objectId": "VWOxzFui6R"
    }
  ],
  "total": 1210,
  "status": "processing",
  ...
}

Which then allows me to include the items in the order query like this query.include('items');

But would there be also a solution how I could use a structure like my first one and still be able to include the products in the order query? It kind of feels "redundant" to have the same product multiple times in an array if the user ordered this product eg 2 or 3 times.

The way this is done in most ecommerce systems is to have another object that adds data to the relationship between order and product, for example...

// Order
{ lineItems: [ <pointer to line item>, < etc > ],
  orderTotal: number,
  // other fields: probably a customer-pointer, tax, shipping, etc
};

// Line Item - this is the missing concept in the OP
{ product: <pointer to product>,
  unitPrice: number,
  quantity: number
};

// Product as you have it

Notice that the unitPrice is probably redundant with a price attribute kept with product. The app would copy the product price to this field when the product is added to the order. This enables a business logic decision abut what to do if the product price changes after the order is created.

The order query can include('lineItems', 'lineItems.product')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM