androidrealmrealm-list

Realm collection query


I want to build a query in realm(java) that satisfies this condition: All the books that have a tag with type X and name like Y. Here my realm classes:

class Book extends RealmObject {

    public RealmList<Tag> tags;

    public int fileType;

    public String title;
}

class Tag extends RealmObject {

    public Book book;

    public int type;

    public String name;
}

I have to use a query based on Book, so the query must begin like this:

realm.where(Book.class)

But I can't build query as I want. I tried this:

realm.where(Book.class)
  .equalTo("tags.type", X)
  .contains("tags.name", Y)
  .findAll();

This query means books that any of it's tags.type equals to X and any of it's tags.name contains Y.

But I wanna apply both condition to same Tag object.

How can I do this?

Thanks.


Solution

  • Link queries can be a bit hard to wrap your head around, but we have a full example with explanations here: https://realm.io/docs/java/latest/#link-queries

    In your case you need to rewrite it into this:

    realm.where(Book.class)
      .equalTo("tags.type", X)
      .findAll().where()
      .contains("tags.name", Y)
      .findAll();