2

我正在尝试寻找一个去SUM关系字段的方法,但总是抛出异常~

那么可以通过使用领域数据库来汇总关系吗?

如果你知道我在哪里写错了,请告诉我,非常感谢:)

假设我有以下数据集:

public class Service extends RealmObject {
    private String id;
    private RealmList<Service> extras;
    private boolean selected;
    // getters and setters
}

public class ServiceExtra extends RealmObject {
    private String id;
    private float price;
    private boolean selected;
    // getters and setters
}

然后,我猜查询代码是这样的

Realm.getDefaultInstance()
     .where(Service.class)
     .equalTo("selected",true)
     .equalTo("extras.selected",true)
     .sum("extras.price");

但总是扔

java.lang.IllegalArgumentException: Field does not exist: extras.price
     at io.realm.RealmObjectSchema.getAndCheckFieldIndex(RealmObjectSchema.java:756)
     at io.realm.RealmQuery.sum(RealmQuery.java:1592)

更新

Realm realm = Realm.getDefaultInstance();
Service service = realm.where(Service.class).equalTo("selected",true).findFirst();
int totalPrice = service.extras.where().equalTo("selected",true).sum("price");

或者

Realm realm = Realm.getDefaultInstance();
RealmResult<Service> services = realm.where(Service.class)
            .equalTo("selected",true).finAll();
int totalPrice;
for(Service service : services){
    totalPrice += service.extras.where()
            .equalTo("selected",true).sum("price");
}
4

1 回答 1

1

尝试以下方法求和,最小值,最大值,平均字段

RealmResults<User> results = realm.where(User.class).findAll();
 long   sum     = results.sum("age").longValue();
 long   min     = results.min("age").longValue();
 long   max     = results.max("age").longValue();
 double average = results.average("age");

 long   matches = results.size();
于 2017-09-19T09:40:03.387 回答