领域查询还过滤嵌套在另一个RealmObject类中的自定义对象数据

时间:2016-10-10 20:17:33

标签: java android realm

我正在尝试在Realm中创建一个查询,该查询过滤掉自身在RealmObject类中的自定义对象数据。所以对于例如:

我有这个班级

public class Email extends RealmObject {

public static final String PROPERTY_SUBJECT = "subject";
public static final String PROPERTY_SENDER = "sender";
public static final String PROPERTY_BODY = "body";

  public String subject;
  public Sender sender;
  public Body body;
  public Date receivedDateTime;
}

public class Sender extends RealmObject {
  public EmailAddress emailAddress;
}

public class EmailAddress extends RealmObject {
  public String emailId;
  public String name;
}

public class Body extends RealmObject {
  public String content;
  public String contentType;
}

所以我正在尝试创建一个查询,它根据用户搜索返回所有结果,以便从“subject,emailAddress,name,bodyContent”进行过滤。

所以我试试这个

Realm realm = Realm.getDefaultInstance();
RealmQuery<Email> query = realm.where(Email.class);

query.beginGroup();
query.contains(Email.PROPERTY_SUBJECT, queryString);
query.contains(Email.PROPERTY_SENDER, ?);
query.contains(Email.PROPERTY_BODY, ?);
query.endGroup();

RealmResults<Email> results = query.findAllSorted(Email.PROPERTY_RECEIVED_DATE_TIME, Sort.DESCENDING);

我试图弄明白我如何将Sender和Body对象放在查询中,因为它们是自定义对象。

我可以帮助我,因为我是Realm的新手吗?

提前谢谢.. :))

3 个答案:

答案 0 :(得分:1)

我弄清楚我在Realm查询中做错了什么。基本上,我没有使用或()运算符来组合多个查询,这就是我无法获得所需结果的原因。

现在我自己解决了这个问题。这是我的解决方案:

    RealmQuery<Email> query = realm.where(Email.class);
    query.contains(Email.PROPERTY_SUBJECT, queryString, Case.INSENSITIVE).or()
        .contains(Email.PROPERTY_SENDER_NAME, queryString, Case.INSENSITIVE).or()
        .contains(Email.PROPERTY_SENDER_EMAIL, queryString, Case.INSENSITIVE).or()
        .contains(Email.PROPERTY_BODY_CONTENT, queryString, Case.INSENSITIVE);
    RealmResults<Email> searchResults = query.findAllSorted(Email.PROPERTY_RECEIVED_DATE_TIME, Sort.DESCENDING);

我的常数是这样的:

  public static final String PROPERTY_SUBJECT = "subject";
  public static final String PROPERTY_SENDER_NAME = "sender.emailAddress.name";
  public static final String PROPERTY_SENDER_EMAIL = "sender.emailAddress.address";
  public static final String PROPERTY_BODY_CONTENT = "body.content";

此外,您可以在查询中看到我添加了Case.INSENSITIVE参数,因为我希望我的搜索不区分大小写。

感谢您向我提供上述建议并尝试帮助我。 :):)

答案 1 :(得分:0)

您可以查看doc about link queries

首先,您的查询似乎不需要beginGroup()endGroup

尝试以下:

Realm realm = Realm.getDefaultInstance();
RealmQuery<Email> query = realm.where(Email.class);

query.contains(Email.PROPERTY_SUBJECT, queryString);
query.contains("sender.emailAddress.name", "john");
query.contains("body.content", "some thing");

RealmResults<Email> results = query.findAllSorted(Email.PROPERTY_RECEIVED_DATE_TIME, Sort.DESCENDING);

答案 2 :(得分:0)

答案是“链接查询”,尽管在您的情况下为you're just supposed to merge the objects into one.

public class Email extends RealmObject {
  private String subject;
  private String senderName;
  private String bodyContent;
  private String bodyContentType;
  private Date receivedDateTime;

  // getters, setters
}