Reputation: 1843
I'm trying to implement a Many-to-many relationship
with Realm
between User
and Chat
objects. I'm following the oficial documentation. Here are my objects.
public class User implements RealmModel {
@PrimaryKey
private String userId;
private String name;
private String phone;
private String pictureURL;
private String thumbnailURL;
private String pushToken;
private String status;
private long lastOnlineMs;
public RealmList<Chat> chats = new RealmList<>();
public User() {}
}
public class Chat implements RealmModel {
@Required
@PrimaryKey
private String chatId;
private long creationDateMs;
private String creatorUserId;
private String name;
@LinkingObjects("chats")
public final RealmResults<User> users = null;
private int chatType;
public Chat() {}
}
Here is the code where I create the Chat
object in the database and add the relation. The users have been correctly created before:
public void addChat(final Chat chat, final User creatorUser, final User opponentUser ) {
realm.executeTransaction(realm -> {
realm.copyToRealmOrUpdate(chat);
creatorUser.chats.add(chat);
opponentUser.chats.add(chat);
});
}
After executing the code User
and Chat
objects are stored in database but chat list
for users are empty.
I also use realm.beginTransaction
that is just a same like executeTransaction
, the difference just execute are thread safe.
I also use realm.insertOrUpdate(obj)
, but just have same result.
Upvotes: 1
Views: 583
Reputation: 2096
copyToRealmOrUpdate
from doc :
Updates an existing RealmObject that is identified by the same {@link io.realm.annotations.PrimaryKey} or a new copy if no existing object could be found
It does not update the RealmObject your are giving as parameter because it's not a managed object yet, so you need to retrieve the returned object that is managed to add it to your users.
public void addChat(final Chat chat, final User creatorUser, final User opponentUser ) {
realm.executeTransaction(realm -> {
Chat managedChat = realm.copyToRealmOrUpdate(chat);
creatorUser.chats.add(managedChat);
opponentUser.chats.add(managedChat);
});
}
Upvotes: 1