我需要有关Realm中LinkingObjects的帮助。请查看以下简单代码:

public class Product extends RealmObject
{
    @PrimaryKey
    private int prodId;

    @Required
    private String name;

    private RealmList<ProductItem> productItems;

    @LinkingObjects("productParent")
    private final RealmResults<ProductItem> linkProductItems = null;
    ...
    ...
    ...
}

public class ProductItem extends RealmObject
{
    @PrimaryKey
    private String primaryKey;

    private int prodId;

    private int prodItemId;

    private String itemCode;

    private double price;

    private Product productParent;
    ...
    ...
    ...
    public Product getProductParent()
    {
        return productParent;
    }
}

然后,通过执行以下操作添加了示例数据:
realm.beginTransaction();

Product prod = new Product();
prod.setProdId(1);
prod.setName("Test");
prod = realm.copyToRealm(prod);

ProductItem prodItem = new ProductItem();
prodItem.setProdId(prod.getProdId());
prodItem.setProdItemId(1);
prodItem.setItemCode("00231");
prodItem.setPrice(9.95);
prodItem.getProductItems().add(realm.copyToRealm(prodItem));

realm.commitTransaction();

现在,据我了解,LinkingObjects允许您引用父级对象?但是以下代码将失败:
String sOutput = "";
for (ProductItem prodItem :  realm.where(ProductItem.class).findAll())
    sOutput += prodItem.getProductParent().getName() + "\n";

问题是 bqItem.getProductParent()为NULL。我的问题是,我是否正确完成了LinkingObjects?如果没有,您能帮我吗?

谢谢

最佳答案

你在找

public class Product extends RealmObject
{
    @PrimaryKey
    private int prodId;

    @Required
    private String name;

    private RealmList<ProductItem> productItems;

    //@LinkingObjects("productParent")
    //private final RealmResults<ProductItem> linkProductItems = null;
    ...
    ...
    ...
}

public class ProductItem extends RealmObject
{
    @PrimaryKey
    private String primaryKey;

    private int prodId;

    private int prodItemId;

    private String itemCode;

    private double price;

    //private Product productParent;

    @LinkingObjects("productItems")   // <-- !
    private final RealmResults<Product> productParents = null; // <-- !
    ...
    ...
    ...
    public RealmResults<Product> getProductParents() // <-- !
    {
        return productParents;
    }
}

07-26 04:53