Blog

How to Register/Update a User With Related Data Object(s)

by on September 1, 2019

Connecting users with their related data is a key function of user management. When you register (or update) a user object, you may need to create a relation between the user and some other entity/object stored in your Backendless Database. Since a user object is structurally a collection of properties, it is very easy to relate an object stored in Backendless with a user.

The code below shows how to register a user with a related object referenced through the “address” property:

    final BackendlessUser user = new BackendlessUser();
    user.setEmail("spiderman@backendless.com");
    user.setPassword("greeng0blin");
    
    Address address = new Address();
    address.setStreet("123 Main St");
    address.setCity("Dallas");
    address.setState("Texas");
    address.setZip("75032");
    
    Backendless.Data.of(Address.class).save(address, new AsyncCallback
    () { @Override public void handleResponse(final Address savedAddress) { Log.i(TAG, “Relation has been created”); Backendless.UserService.register(user, new AsyncCallback() { @Override public void handleResponse(BackendlessUser registeredUser) { Log.i(TAG, “User has been registered”); Backendless.Data.of(BackendlessUser.class).setRelation(registeredUser, “address:Address:1”, Collections.singleton(savedAddress), new AsyncCallback() { @Override public void handleResponse(Integer response) { Log.i(TAG, “Relation has been set”); } @Override public void handleFault(BackendlessFault fault) { Log.e(TAG, fault.getMessage()); } }); } @Override public void handleFault(BackendlessFault fault) { Log.e(TAG, fault.getMessage()); } }); } @Override public void handleFault(BackendlessFault fault) { Log.e(TAG, fault.getMessage()); } });

    val user = BackendlessUser()
    user.email = "spiderman@backendless.com"
    user.password = "greeng0blin"
    
    val address = Address()
    address.street = "123 Main St"
    address.city = "Dallas"
    address.state = "Texas"
    address.zip = "75032"
    
    Backendless.Data.of(Address::class.java).save(address, object : AsyncCallback
    { override fun handleResponse(savedAddress: Address) { Log.i(TAG, “Relation has been created”) Backendless.UserService.register(user, object : AsyncCallback { override fun handleResponse(registeredUser: BackendlessUser) { Log.i(TAG, “User has been registered”) Backendless.Data.of(BackendlessUser::class.java).setRelation( registeredUser, “address:Address:1”, listOf(savedAddress), object : AsyncCallback { override fun handleResponse(response: Int?) { Log.i(TAG, “Relation has been set”) } override fun handleFault(fault: BackendlessFault) { Log.e(TAG, fault.message) } }) } override fun handleFault(fault: BackendlessFault) { Log.e(TAG, fault.message) } }) } override fun handleFault(fault: BackendlessFault) { Log.e(TAG, fault.message) } })

    Address *address = [Address new];
    address.state = @"Texas";
    address.city = @"Dallas";
    address.zip = @"75032";
    address.street = @"123 Main St";
        
    BackendlessUser *user = [BackendlessUser new];
    user.email = @"green.goblin@backendless.com";
    user.password = @"greeng0blin";
        
    [[Backendless.shared.data of:[Address class]] saveWithEntity:address responseHandler:^(Address *savedAddress) {
            
        [Backendless.shared.userService registerUserWithUser:user responseHandler:^(BackendlessUser *registeredUser) {
                
            [[Backendless.shared.data of:[BackendlessUser class]] setRelationWithColumnName:@"address:Address:1" parentObjectId:registeredUser.objectId childrenObjectIds:@[savedAddress.objectId] responseHandler:^(NSInteger relationSet) {
                NSLog(@"Relation has been set");
            } errorHandler:^(Fault *fault) {
                NSLog(@"Error: %@", fault.message);
            }];
                
        } errorHandler:^(Fault *fault) {
            NSLog(@"Error: %@", fault.message);
        }];
            
    } errorHandler:^(Fault *fault) {
        NSLog(@"Error: %@", fault.message);
    }];

    let address = Address()
    address.state = "Texas"
    address.city = "Dallas"
    address.zip = "75032"
    address.street = "123 Main St"
            
    let user = BackendlessUser()
    user.email = "green.goblin@backendless.com"
    user.password = "greeng0blin"
            
    Backendless.shared.data.of(Address.self).save(entity: address, responseHandler: { savedAddress in
                
        Backendless.shared.userService.registerUser(user: user, responseHandler: { registeredUser in
                    
            if let savedAddress = savedAddress as? Address,
                let addressId = savedAddress.objectId,
                let userId = registeredUser.objectId {
                Backendless.shared.data.of(BackendlessUser.self).setRelation(columnName: "address:Address:1", parentObjectId: userId, childrenObjectIds: [addressId], responseHandler: { relationSet in
                    print("Relation has been set")
                }, errorHandler: { fault in
                    print("Error: \(fault.message ?? "")")
                })
            }
                    
        }, errorHandler: { fault in
            print("Error: \(fault.message ?? "")")
        })
                
    }, errorHandler: { fault in
        print("Error: \(fault.message ?? "")")
    })

    const Backendless = require('backendless')
    /*
     Or use `import Backendless from 'backendless'` for client side.
     If you don't use npm or yarn to install modules, you can add the following line
     <script src="//api.backendless.com/sdk/js/latest/backendless.min.js"></script>
     to your index.html file and use the global Backendless variable.
    */
    
    Backendless.initApp('YOUR_APP_ID', 'YOUR_JS_API_KEY')
    
    const user = new Backendless.User()
    
    user.email = 'spiderman@backendless.com'
    user.password = 'greeng0blin'
    
    const address = {
      street: '123 Main St',
      city  : 'Dallas',
      state : 'Texas',
      zip   : '75032',
    }
    
    const onSuccess = user => {
      console.log('User has been registered')
      console.log(user)
    }
    
    const onError = error => {
      console.error('Server reported an error: ', error.message)
      console.error('error code: ', error.code)
      console.error('http status: ', error.status)
    }
    
    const registerUser = async (user, address) => {
      const [newUser, userAddress] = await Promise.all([
        Backendless.UserService.register(user),
        Backendless.Data.of('Address').save(address)
      ])
    
      await Backendless.Data.of('Users').setRelation(newUser, 'address', [userAddress])
    
      return newUser
    }
    
    registerUser(user, address)
      .then(onSuccess)
      .catch(onError)
    

    BackendlessUser user = BackendlessUser()
       ..email = "spiderman@backendless.com"
       ..password = "greeng0blin";
    
       Map address = {
         "street": "123 Main St",
         "city": "Dallas",
         "state": "Texas",
         "zip": "75032"};
    
       Backendless.Data.of("Address").save(address).then((savedAddress) {
         print("Relation has been created");
    
         Backendless.UserService.register(user).then((registeredUser) {
           print("User has been registered");
    
           Backendless.Data.of("Users").setRelation(registeredUser.toJson(),
             "address:Address:1", children: [savedAddress]
           ).then((response) => print("Relation has been set"));
         });
       });

    Once you run the code above, the Users table shows the registered user and a link to the related Address object:

    Leave a Reply