我有一个像这样的领域对象
public class MyItem extends RealmObject {
public Product product;
public double amount;
}
public class Product extends RealmObject {
public double price;
}
我想按MyItem(product.price * amount)升序排序我的领域列表。 Realm如何实现这一目标?
答案 0 :(得分:1)
public class MyItem extends RealmObject {
private double price;
private double amount;
private double total;
// getters for price/amount
public void setPrice(double price) {
this.price = price;
this.total = price * amount;
}
public void setAmount(double amount) {
this.amount = amount;
this.total = price * amount;
}
}
然后
realm.where(MyItem.class).findAllSorted("total", Sort.ASCENDING);
编辑:通过修改,适用相同的规则。
public class MyItem extends RealmObject {
private Product product;
private double amount;
private double totalPrice;
void updateTotalPrice() {
if(product == null) {
totalPrice = 0;
} else {
totalPrice = amount * product.getPrice();
}
}
public void setProduct(Product product) {
this.product = product;
updateTotalPrice();
}
public void setAmount(double amount) {
this.amount = amount;
updateTotalPrice();
}
}
public class Product extends RealmObject {
private double price;
@LinkingObjects("product")
private final RealmResults<MyItem> items = null;
public void setPrice(double price) {
this.price = price;
if(items != null) { // updates to existing object should happen only via managed objects!
for(MyItem item : items) {
item.updateTotalPrice();
}
}
}
}
然后
realm.where(MyItem.class).findAllSorted("totalPrice", Sort.ASCENDING);