Realm realtionships and duplicate data

602 views
Skip to first unread message

Faisal Abid

unread,
Feb 3, 2015, 11:58:21 AM2/3/15
to realm...@googlegroups.com
Running into some weird issues with duplicate data.

I have 3 tables

Movies

Users

and WatchedByUser

Both movies and users are independent of each other, but when a user does watch a movie. I make a query for the movie object and a query for the user object and add it to a WatchedByUser object.

realm.beginTransaction();

user = realm.where
movie = realm.where

WatchedByUser wbu = new WatchedByUser();
wbu.setUser(user);
wbu.setMovie(movie);

realm.copyToRealm(wbu);

realm.commitTransaction();


All works great. but now in my movie table and user table, there are two copies of the User and Movie.

How do i prevent that from happening? I just want to link the objects, not create copies of it.

Emanuele Zattin

unread,
Feb 3, 2015, 2:00:35 PM2/3/15
to Faisal Abid, realm...@googlegroups.com
Hello Faisal,

that's an interesting use-case!

A couple of notes:

1) In Realm you don't need an extra model class to keep track of many-to-many relationship, as you do in a relational database. All you need is something like this:

Movie:
* title
* RealmList<User> watchers; // you only need this field if you need queries going in the other direction as well

User:
* name
* RealmList<Movie> moviesWatched.

2) The duplication or objects happens because you are using standalone objects to insert the data. SInce primary-keys are not available yet (soon!) there's no way for Realm to know if it's actually the same user and movie you are inserting, so it adds a new one.
Also bear in mind that using standalone objects is a waste of memory.
One way to do it, given for the sake of the argument you want to keep the WatchedByUser class, is something like:

User user = realm.where(User.class)....
Movie movie = realm.where(Movie.class)....

realm.beginTransaction();
WatchedByUser wbu = realm.createObject(WatchedByUser.class);
wbu.setUser(user);
wbu.setMovie(movie);
realm.commitTransaction();

Does this help you?

--
Emanuele Zattin



--
You received this message because you are subscribed to the Google Groups "Realm Java" group.
To unsubscribe from this group and stop receiving emails from it, send an email to realm-java+...@googlegroups.com.
To post to this group, send email to realm...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/realm-java/d0aed236-64a5-42c7-8139-e1d6b6cb41d7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



{#HS:69279388-431#}

Faisal Abid

unread,
Feb 3, 2015, 2:33:27 PM2/3/15
to realm...@googlegroups.com, faisa...@gmail.com, he...@realm.io
Ah interesting, these are good pointers. I think this helps me out a lot. I'll give it a spin!
Reply all
Reply to author
Forward
0 new messages