【问题标题】:How to save only RealmObject but not referenced object如何只保存 RealmObject 但不保存引用的对象
【发布时间】:2016-11-08 12:06:42
【问题描述】:

在我的应用程序中,我有以下 RealmObjects:

产品 - 作为主数据,永远不应修改。
购物车 - 购物车,允许人们挑选要购买的东西。内容将是选择类型。
选择 - 表示用户选择的产品以及颜色、尺寸等额外偏好。

用例
用户选择产品并添加到购物车。产品被包裹在 Selection 中并存储在 Cart 中。说选择产品 A、B 和 C。

现在将其保存到 Realm 中。文档告诉我使用RealmList 添加关系。这使得购物车 -> 列表;选择 -> 产品。

如果我使用copyToRealm,我会得到Product 上的PrimaryKey 异常。 由于我想保存仅购物车和选择,我如何使选择链接到产品(用于阅读备份)但不保存它。

如果我使用copyToRealmOrUpdate,我是否有意外更新产品的风险?

【问题讨论】:

    标签: android realm realm-list


    【解决方案1】:

    您可以从一开始就在领域内显式创建领域对象,并将对象链接设置为托管对象内的托管对象。

    realm.executeTransaction((realm) -> {
        // ASSUMING PRIMARY KEY
        Selection selection = realm.where(Selection.class).equalTo(SelectionFields.ID, selectionId).findFirst();
        if(selection == null) {
           selection = realm.createObject(Selection.class, selectionId);
        }
        // here, selection is always managed
    
        //...
        Product product = realm.where(Product.class)./*...*/.findFirst();
        selection.setProduct(product);
    
        // no insertOrUpdate()/copyToRealmOrUpdate() call for `selection`
    });
    

    但您也可以在代理转为托管后设置产品链接。

    realm.executeTransaction((realm) -> {
        Selection selection = new Selection();
    
        // assuming selection.getProduct() == null
    
        selection = realm.copyToRealmOrUpdate(selection);
        // selection is now managed
    
        Product product = realm.where(Product.class)./*...*/.findFirst();
        selection.setProduct(product);
    
        // no insertOrUpdate()/copyToRealmOrUpdate() call for `selection`
    });
    

    【讨论】:

    • 我最终选择了后一种选择。对我来说主要的抱怨是现在我必须在 Selection 对象中保留 product 和 productId 字段。
    【解决方案2】:

    如果您不想存储 Product,那么您可以只将它的 ID 存储在您的对象中。如果您将使用copyToRealmOrUpdate - 您可能会意外更新您的对象,因为此方法执行深度复制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 2013-11-20
      • 2013-07-09
      • 2019-08-31
      相关资源
      最近更新 更多