How can I create a many-to-many relationships using Realm database on Android? For example, I need two types of objects: PostObject and HashTagObject, linked one to the other, something like this.
public class PostObject extends RealmObject {
@PrimaryKey
private int id;
private String text;
private RealmList<HashTagObject> hashtags;
}
public class HashTagObject extends RealmObject {
@PrimaryKey
private int id;
private String tag;
private RealmList<PostObject> posts;
}
I want to be able to create a post and to attach a hashtag to it, while also being able to get the posts that use the hashtag. Is that the correct implementation? How do I create a hashtag or use the existing one, if I already have it?
When I create new post I do:
realm.beginTransaction();
PostObject post = realm.createObject(PostObject.class);
post.setText("New post");
HashTagObject tag = realm.createObject(HashTagObject.class);
tag.setTag("tag");
tag.getPosts().add(post);
post.getTags().add(tag);
realm.commitTransaction();
When I create another I do the same.
As I understand, this one will create new hashtag every time and in the end I will have two hashtag objects with the tag "tag", while I want to have only the one hashtag "tag".