【问题标题】:Android: Realm understand LinkingObjectsAndroid:Realm 理解 LinkingObjects
【发布时间】:2023-03-09 20:30:02
【问题描述】:

我需要有关 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?如果没有,你能帮帮我吗?

谢谢

【问题讨论】:

  • 你能在 tblProductItem 类中试试private tblProduct tblProductParent = new tblProduct();
  • 什么是BanquetItem?以上代码为ProductItem?
  • @EpicPandaForce, upsss... 抱歉... LOL... 从错误的项目中复制并粘贴错误的代码。我已经更正了代码。它应该是 ProductItem。

标签: java android orm realm


【解决方案1】:

你正在寻找

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;
    }
}

【讨论】:

  • 是否存在parent会返回null的情况?我现在遇到这样一个问题,当我询问它的父对象时,子对象返回 null。
  • 不,他们没有
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多