Update with Adding a Relation¶
The Deep Save API can be used to update an existing object and set a relation with a new child (or parent). Consider the examples below:
Existing Parent and New Child¶
This example retrieves an existing parent object (Order
) and uses the Deep Save API to perform the following:
- Save new child object (
OrderItem
) - Establish relationship between the
Order
and the newOrderItem
.
The Order
object already has two related OrderItem
objects before the sample code below runs:
Important
When working with relationships, the Deep Save API applies the "accumulation" policy. This means the following: if a parent object in the database already has some related objects and you update the object with new child objects in the relation, these objects will be added to the relation.
// get the order with the relations.
const order = await Backendless.Data.of('Order').findFirst()
// create new order item
const grapes = { name: 'Grapes', price: 3.99 }
const orderItems = []
// add grapes to the existing order items on the server
orderItems.push(grapes)
// put the list with grapes added to it back into order
order.orderItems = orderItems
// deep save the order
Backendless.Data.of('Order').deepSave(order)
// get the order object.
const order = await Backendless.Data.of(Order).findFirst()
// create new order item
const grapes = new OrderItem({ name: 'Grapes', price: 3.99 })
// add new order item to the existing ones
order.addItem(grapes)
// deep save the order
Backendless.Data.of(Order).deepSave(order)
class Order {
constructor(data) {
data = data || {}
this.objectId = data.objectId
this.customer = data.customer
this.orderItems = data.orderItems || []
}
addItem(item) {
this.orderItems.push(item)
}
}
class OrderItem {
constructor(data) {
data = data || {}
this.name = data.name
this.price = data.price
}
}
After the code runs, the new OrderItem
object is saved in the database and the Order
object relation is expanded to include it: