使用GroupBy进行Realm.io查询

时间:2015-05-25 04:23:01

标签: java android sql orm realm

我想按月对一些帐户进行分组,我可以使用Realm.io吗?

public class Account extends RealmObject {
.....
 private Date date;
}

RealmResults accounts = realm.where(Account.class)
.beginGroup()
.equalTo("date", "MONTH(date)")//<----- wrong code
.endGroup()
.findAll();

感谢

1 个答案:

答案 0 :(得分:3)

Realm还不支持GroupBy。还要注意,beginGroup()实际上与括号相同。因此,您的查询实际上被解释为:

// SQL pseudo code
SELECT * FROM Account WHERE (date = MONTH(date))

在Realm中你必须做这样的事情来选择一个月:

// Between is [ monthStart, monthEnd ] 
Date monthStart = new GregorianCalendar(2015, 5, 1).getTime();
Date monthEnd = new GregorianCalendar(2015, 6, 1).getTime() - 1;
accounts = realm.where(Account.class).between("date", monthStart, monthEnd).findAll();

或类似的东西来检测月份何时发生变化

// pseudo code. You might want to use Calendar instead
accounts = realm.where(Account.class).findAllSorted("date")
Iterator<Account> it = accounts.iterator();
int previousMonth = it.next().getDate().getMonth();
while (it.hasNext) {
  int month = it.next().getDate().getMonth();
  if (month != previousMonth) {
    // month changed
  }
  previousMonth = month;
}