Search code examples
androidrealmone-to-many

Android Realm adding objects to existing one to many relationship


I'm running into an issue with Realm, one to many relationship and updating existing entries to add more data to the relationship.

Model 1

public class Model1 extends RealmObject
{
    @PrimaryKey
    private String identifier;

    @SerializedName("type")
    private String type;

    @SerializedName("additionalInfo")
    private String additionalInfo;

    @SerializedName("options")
    private RealmList<Model2> moreModels;

}

Model 2

public class Model2 extends RealmObject
{
    @SerializedName("hint")
    private String hint;

    @SerializedName("label")
    private String label;

    @SerializedName("favorite")
    private boolean favorite;

    @PrimaryKey
    private String identifier;
}

So from an API I'm getting a list of Model1 objects, and each of those objects contains their own list of Model2 objects. Simple enough. This works well, I can add it to Realm and see the relationship.

Now my problem emerges when I make a second API call for a different user. The way I was hoping to have this work was to have the identifier property on Model2 be made up of userId + label. Therefore, each user will have their own set of Model2 objects. However, I was hoping to have only one set of Model1 objects, where its reference to Model2 objects gets updated as more are added to the Model2 table.

Instead what I got working is I keep my one set of Model1 (good), but the relationship to Model2 always gets overwritten with the latest set. So I have a table of Model2 objects that has 80 entries, but only the last 40 are connected.

So it looks like my update or insert is updating the Model1 entries in the table (GOOD) but instead of concatenating the existing relationships with the new ones, its just updating the relationships to only use the new ones. The Model2 entries are being added to their table correctly in that there are not duplicates based on the primary key. But the connection is broken.

Update Code

List<Model1> test = response.body();

try(Realm realmInstance = Realm.getDefaultInstance()) {
    realmInstance.executeTransaction((realm) ->
        {
            realm.insertOrUpdate(test);

            final RealmResults<Model> category = realm.where(Model1).findAll(); 
        }
    );
}

Solution

  • Yes, that is how the insertOrUpdate and copyToRealmOrUpdate methods works currently. Ideally, there would be a mode you could provide like REPLACE_LISTS or MERGE_LISTS, but right now that hasn't been implemented.

    Your only choice is manually updating these relationships.