0

I am a bit confused with the documentation. Let's stay with the customer order relationship, where a customer can have n orders.

If I create a new order for an existing customer and store this with

Customer customer = Customer();
customer.orders.add(Order()); // Order #3
customer.orders.add(Order()); // Order #4
// Puts customer and orders:
final customerId = store.box<Customer>().put(customer);

I expect this to update the customer (overwriting all data) because I am using the id of the customer. And I guess, the new orders #3 and #4 are created as new orders and linked to the customer, because their order id is 0. But what happens with my orders I have stored previously (#1 & #2)? Do they remain linked to my customer? Or is this link overwritten as well and as such lost?

w461
  • 2,168
  • 4
  • 14
  • 40

1 Answers1

1

As is, your code example would create a new customer. To update an existing customer and its relation, first get the existing customer from the store (or re-use the previously put customer instance).

Customer customer = store.box<Customer>().get(customerId);
customer.orders.add(Order()); // Order #3
customer.orders.add(Order()); // Order #4
store.box<Customer>().put(customer);

The documentation also shows how to get and remove objects from a ToMany relation.

Uwe - ObjectBox
  • 1,012
  • 1
  • 7
  • 11
  • `Customer customer = Customer();` was a copy-paste error. Of course customer needs to come from the ObjectBox with the id. But the question whether updating this with only customer and order 3 & 4 will keep the relation to order 1 & 2 remains. Anyways, since relations in ObjectBox do not support my layered architecture so well (with transforming nested data types), I meanwhile store nested data as a json string and not as a relation – w461 Sep 13 '21 at 09:19
  • 1
    When you get the `Customer` from the database the ToMany contains existing related objects. If you remove them and only add order 3 and 4 the relation to order 1 and 2 will be dissolved when putting the `Customer`. – Uwe - ObjectBox Sep 14 '21 at 05:36