3ISvZFqczFBVUtz 3ISvZFqczFBVUtz - 2 months ago 17
Android Question

Access parent from child in Realm for Android

I am creating a chat application using Realm 1.2.0 for Android.

Here are two minimized models I created:

public class Room extends RealmObject {

private String name;

private RealmList<Message> messages;

}

public class Message extends RealmObject {

@PrimaryKey
private long id;

private String text;

}


Using these models, I can get all messages in a specific room. The problem is, I also want to access the room from a message.

For example, this would be possible (accessing the childs from the parent):

room.getMessages()


But I also want to access the parent from the child, like this:

message.getRoom()


Is this possible in Realm without manually querying all the rooms again?

Answer

The concept is called backlink, and they're not in yet. In fact, they're in design stage or so, so it'll take a while before automatic inverse relationships are available.

So currently you'd need to maintain both sides of the relationship yourself.

public class Room extends RealmObject {

    private String name;

    private RealmList<Message> messages;

}

public class Message extends RealmObject {

    @PrimaryKey
    private long id;

    private String text;

    private Room room;
}

r.executeTransaction((realm) -> {
  Room room = realm.where(Room.class).equalTo("name", name).findFirst();
  Message message = new Message();
  message.setId(getNextId());
  message.setText(text);
  message.setRoom(room);
  message = realm.copyToRealmOrUpdate(message);
  room.getMessages().add(room);
}
Comments