Create object with existing relation using REST and JS

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"
  }
}

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

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

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.

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?

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

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.

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.

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?

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

Wonderful! That works perfectly.

Thank you Mark.