有可能总结关系领域吗? [使用领域]

时间:2017-03-11 04:46:29

标签: realm-java

我试图找到一个关于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");
}

1 个答案:

答案 0 :(得分:0)

尝试以下内容来求和,最小,最大,平均字段

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();