【问题标题】:Relational database in Realm?Realm中的关系数据库?
【发布时间】:2017-02-08 06:40:59
【问题描述】:

我想在 iOS Realm DB 中创建简单的关系数据库。我如何链接用户 ID 和愿望清单产品,类似于 SQL 中的关系数据库。示例如下图:

我知道我可以创建 2 个单独的 Realm 模型(表)来存储带有 time_stamp 的用户 ID,并在愿望清单的第二个表中存储每个愿望清单产品的用户 ID 或用户 ID 和一个愿望清单,其中用户有一个数组愿望清单。现在我想存储所有用户有多个愿望清单。这意味着每次用户进入 APP 时,我都必须查询存在的每个愿望清单,以查看其是否针对此特定愿望清单。问题出在 Wishlist 表中,它没有任何主键和领域,不允许在没有主键的情况下创建模型。

Realm 是否支持外键概念? 并且复合键的使用非常复杂。有没有更有效的方法来做到这一点?

【问题讨论】:

    标签: ios objective-c realm


    【解决方案1】:

    您可以使用 RLMArray ,其中 RLMArray 是 Realm 中用于定义对多关系的容器类型。 正如官方 Realm 文档中提到的目标 c 检查示例 here。 也通过这个链接它可能会帮助RLMArray doc

    【讨论】:

      【解决方案2】:

      RLMArray 用于领域中的关系数据库概念。你可以这样尝试:

      #import <Realm/Realm.h>
      
      @class User;
      
      // User model
      @interface User : RLMObject
      @property NSString *name;
      @property NSString *user_id;
      @property RLMArray<Watchlist *><Watchlist> *watchlist;
      @end
      RLM_ARRAY_TYPE(Dog) // define RLMArray<Dog>
      
      // Watchlist model
      @interface Watchlist : RLMObject
      @property NSString *id;
      @property NSInteger *activity;
      @property NSInteger *cost;
      
      @end
      RLM_ARRAY_TYPE(Watchlist) // define RLMArray<Person>
      
      // Implementations
      @implementation User
      @end // none needed
      
      @implementation Watchlist
      @end // none needed
      

      从领域读取数据:

      RLMResults *watchlistDB = [Watchlist allObjects];
      WatchlistDB = [realm_data objectAtIndex:index];
      RLMArray *realm_array = WatchlistDB.watchlist;
      

      【讨论】:

      • 你也可以使用linkingObjectsProperties。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 2012-05-31
      相关资源
      最近更新 更多