Backendless Support
 
Answered

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.

  1. {
  2. "title": "TESTING",
  3. "details": "These are the details",
  4. "category": {
  5. "___class":"Category",
  6. "objectId": "91ACFC26-4476-703C-FF00-C09115567D00"
  7. }
  8. }

Leave a Comment

Comments (10)

photo
1

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

photo
1

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.

photo
1

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?

photo
1

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

photo
1

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.

photo
1

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.

photo
1

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?

photo
1

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:

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

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

  1. req.context.crossHandlerData.categoryChannel

photo
1

Wonderful! That works perfectly.

Thank you Mark.

photo