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);
啊!而已。我正在考慮這些方針,但會以可怕的方式實施它。雖然我的問題稍微複雜一點。抱歉,我編輯了這個問題。現在你可能會看到我的困境,對於嵌套對象,getters和setter不是很容易完成的。 – Gravychain
是的,就是這樣。我的產品有很多其他的東西,比如重量,顏色,尺寸等等,但是你可以舉一個單向鏈接的例子。這聽起來像是直接離開星球大戰兄弟 – Gravychain
我實際上意識到我認爲我理解你的用例,並需要一種不同的方法。也是凌晨3點,但我會把這個東西放在一起,然後讓自己休息 – EpicPandaForce