Understanding Realm Reverse Relationships

Asked 2 years ago, Updated 2 years ago, 74 views

This is a very rudimentary question...
I can't really understand the convenience of Realm's "reverse relationship" even after reading some examples of reference books.
I would appreciate it if you could let me know any examples that helped me understand Realm's "reverse relationship".

realm

2022-09-30 19:33

1 Answers

It's not something you must use, so if you don't have to use it, you don't have to worry about it, but I'll explain it using an example of convenience in this case.

Suppose you create a Twitter app.
Simplify the model for clarity and consider only Tweet and User as shown below.

class Tweet:Object {
    dynamic var text=""
    dynamic var creationDate=Date()
    dynamic var user —User?
}

classUser:Object {
    dynamic var name=""
}

The Tweet class has a one-to-one relationship with the user who made the tweet.
The data to display the timeline (list of tweets) is as follows:

let timeline=realm.objects (Tweet.self)
                    .sorted (byKeyPath: "creationDate", ascending: false)

Tweet is taken and sorted in chronological order, starting with the new one.

At this time, when you tap a user on the timeline screen, you want to display a list of tweets for that user.I think it's a common specification.

If there is a reverse association, you can automatically retrieve the Tweet object that the user is associated with from each User instance.This is the reverse related convenience.

Add properties indicating reverse association to the first model.

class Tweet:Object {
    dynamic var text=""
    dynamic var creationDate=Date()
    dynamic var user —User?
}

classUser:Object {
    dynamic var name=""
    let tweets = LinkingObjects (fromType: Tweet.self, property: "user")
}

The tweets property was added to the User class. The tweets property is inversely related to the user property in Tweet, so it represents the reverse direction of the user associated with it, or all tweets.

let tweet=timeline [indexPath.row]
let selectedUser=tweet.user

For example, if you select a user of a tweet as shown above, you can view all of his tweets on the next screen.

let allTweetsOfTheUser=selectedUser?.tweets

Simply follow the tweet property of the User class as shown in
If there is no reverse correlation, you need to manage the reverse correlation yourself if you need this data.Relevant management in the reverse direction must be done as a set when associating User with Tweet, so you need to be careful about the integrity of the data.
Considerations should also be taken when the association is deleted.Resolving those difficulties is the opposite link.


2022-09-30 19:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.