Relational database in Realm?

我的未来我决定 提交于 2019-12-09 23:36:04

问题


I want to create simple relational database in the iOS Realm DB. How can i link user id and there Wishlist product similar to the relational database in SQL. Example like bellow image :

I know i can create 2 separate Realm models (tables) to store user id with time_stamp and in second table for Wishlist where there are user id with each Wishlist products or user id and a Wishlist, where the user has an array of Wishlist. Now i want to store all users with there multiple wishlists. This means that every time the user enters in APP, I have to query every wishlists in existence to see whether its intended for this specific wishlists. The problem is in Wishlist table, it doesn't have any primary key and realm not allowing to create model without primary key.

Does Realm support foreign key concept ? and use of composite key is quit complicated. Is there a more efficient way to do this?


回答1:


You can use RLMArray , where RLMArray is the container type in Realm used to define to-many relationships. As mentioned in the official Realm documentation for objective c check example here. Also go through this link it might help RLMArray doc




回答2:


RLMArray is used for the relational database concept in realm. You can try like this:

#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

Read data from realm :

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


来源:https://stackoverflow.com/questions/42106351/relational-database-in-realm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!