Adarsh V C
Adarsh V C

Reputation: 2314

How to create relationship in RealmSwift?

I am less experienced in non relational database architecture. My use-case is as follows.

I have an Appointment, and Customer Realm object Model.

Appointment properties are id and relatedCustomer(Customer Model). Customer properties are id and name

I fetch a list of appointments from server and it will add relatedCustomer in the Realm table as a relation of Appointment object.

Later, I fetch the list of customers from another API call and it will add more customers to the Customer Realm table. After fetching the customer list data from server and before creating the customer realm objects, I clear all the previously saved customer objects to make sure that no orphan customer object(Customers that got deleted in the server but available in my realm cache) are displayed in the UI. This bulk deletion is removing my related customer of the Appointment.

How can I handle this?

Upvotes: 2

Views: 873

Answers (1)

AustinZ
AustinZ

Reputation: 1787

Unfortunately, this is a use case that isn't straightforward in Realm.

I suggest that (if you haven't already done so) you make id on your customer model (I'll call it Customer) the primary key property for that model.

Once you do that, here's one possible solution.

When you fetch your list of customers from your server, I presume you'll get a JSON, XML, Swift dictionary, or similar data structure that'll contain a list of customers. From that list of customers, create a Swift Set of id strings, one for each customer.

Then use Realm's objects() API to get a list of all the Customer objects in your Realm. You can then use Swift's map() method to turn that list of existing customers into a Set of id strings.

Now that you have two sets, you can use the subtracting() method on Set to get a list of all the ids that you need to remove (the ids for customers in your Realm, but not in your server data). Then you can remove those objects from the Realm.

Finally, you can use Realm's add(_:update:) method to add all the new customers in, and update the existing users.

You may also want to investigate whether or not your server API could be changed to give you a list of users to delete relative to the list provided the last time you queried it.

Upvotes: 2

Related Questions