RobGThai
RobGThai

Reputation: 5969

How to save only RealmObject but not referenced object

In my app I has the following RealmObjects:

Product - This act as master data and should never be modified.
Cart - Shopping Cart to allow people to pick stuff to buy. The content will be Selection type.
Selection - Represent Product that user selected alongside extra preferences such as color, size, etc.

Use Case
User select Product and add to Cart. Product get wrapped inside Selection and stored inside Cart. Say the pick Product A, B, and C.

Now to save that into Realm. Document tells me to use RealmList to add relationship. That makes Cart -> List; Selection -> Product.

Then if I use copyToRealm, I'll get PrimaryKey exception on Product. Since I want to save only Cart and Selection, how do I make Selection link to Product(For reading back up) but not saving it.

If I use copyToRealmOrUpdate, do I risk accidentally updating the Product?

Upvotes: 2

Views: 323

Answers (2)

Maksim Ostrovidov
Maksim Ostrovidov

Reputation: 11058

If you don't want to store Product then you can store only it IDs inside your objects. If you will use copyToRealmOrUpdate - you may accidentally update your object, because this method performs deep copy.

Upvotes: 1

EpicPandaForce
EpicPandaForce

Reputation: 81539

You can create the RealmObject explicitly inside the Realm from the start, and set the object link to a managed object inside your managed object.

realm.executeTransaction((realm) -> {
    // ASSUMING PRIMARY KEY
    Selection selection = realm.where(Selection.class).equalTo(SelectionFields.ID, selectionId).findFirst();
    if(selection == null) {
       selection = realm.createObject(Selection.class, selectionId);
    }
    // here, selection is always managed

    //...
    Product product = realm.where(Product.class)./*...*/.findFirst();
    selection.setProduct(product);

    // no insertOrUpdate()/copyToRealmOrUpdate() call for `selection`
});

But you can also set the product link only after you turned the proxy to managed.

realm.executeTransaction((realm) -> {
    Selection selection = new Selection();

    // assuming selection.getProduct() == null

    selection = realm.copyToRealmOrUpdate(selection);
    // selection is now managed

    Product product = realm.where(Product.class)./*...*/.findFirst();
    selection.setProduct(product);

    // no insertOrUpdate()/copyToRealmOrUpdate() call for `selection`
});

Upvotes: 2

Related Questions