使用GroupBy进行Realm.io查询

sch*_*sch 6 java sql orm android 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();
Run Code Online (Sandbox Code Playgroud)

谢谢

Chr*_*ior 4

Realm 尚不支持 GroupBy。另请注意,beginGroup() 实际上与括号相同。所以你的查询实际上被解释为:

// SQL pseudo code
SELECT * FROM Account WHERE (date = MONTH(date))
Run Code Online (Sandbox Code Playgroud)

在 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();
Run Code Online (Sandbox Code Playgroud)

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

// 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;
}
Run Code Online (Sandbox Code Playgroud)