Support Topics Documentation Slack YouTube Blog

Create object with existing relation using REST and JS


(Gabriel) #1

Hello,

I am trying to add a new Notification object with an existing Category relation.
Here is my JSON body, what am I doing wrong?

This creates the Notification, but the Category is NULL.


{
  "title": "TESTING",
  "details": "These are the details",
  "category": {
    "___class":"Category",
    "objectId": "91ACFC26-4476-703C-FF00-C09115567D00"
  }
}

(Sergey Chupov) #2

https://backendless.com/docs/js/doc.html#data_relations_api_set_add_js


(Gabriel) #3

Not sure how this help? I am trying to do it using REST.


(Sergey Chupov) #4

https://backendless.com/docs/rest/doc.html#data_relations_save_update

Relations are not saved along with the parent object in version 4. You need to use separate API to establish a relation between the objects.


(Gabriel) #5

Ok, how can I assign an existing relation to a new object using javascript? Are you saying that the new object has to be created first before setting relations to it?


(Mark Piller) #6

That’s correct. Both “parent” and “children” objects must be saved in the database at the time when you establish a relation between them.


(Gabriel) #7

Oh! That is not good for my scenario.

This is what I am trying to do. I create a Notification object and I pass it along a channel name which is a unique key of the Category table.

In the beforeCreate<Notification> event, I find the appropriate Category for that channel and I set the new Notification category relation to it.

That’s how I did it in version 3. How should I do it using version 4?

Thanks for your help.


(Mark Piller) #8

If you move that logic into afterCreate, you should be able to establish a relation between Notification and Category there using the add/setRelation API.


(Gabriel) #9

That will not work, since I won’t know which Category to relate the Notification to. In the before trigger, I was able to get the item.category.channel to get the correct Category.

The after trigger, I will not have that information any more, therefore, I won’t know which Category to get.

ANy other ideas?


(Mark Piller) #10

That’s not a problem. Backendless provides a way to pass data from the “before” to the “after” handler. We call it “crossHandlerData”. Here’s how you could use it in JS business logic:

Backendless.ServerCode.Persistence.beforeCreate('Notification', function(req) {
  req.context.crossHandlerData = {"categoryChannel":item.category.channel};
});

Then in the after handler you can access the value with:

req.context.crossHandlerData.categoryChannel

(Gabriel) #11

Wonderful! That works perfectly.

Thank you Mark.