gonzalezreal / Groot

From JSON to Core Data and back.
Other
534 stars 61 forks source link

Add relationships by merging with existing ones #73

Open Heia- opened 7 years ago

Heia- commented 7 years ago

This is more of a feature request than a bug, and is the only thing preventing Groot from doing exactly what my App needs. As it stands all relationships are treated as complete/perfect relationships, which is not always the case.

Feature: Be able to set an annotation on a relationship that flags it to not override existing relationships but instead merge them.

For example, my situation requires that certain objects be attached to the current logged in User object. These objects may already be attached to another User and as such need to retain that relationship post mapping.

I have been trying to work on my own fork to get this to work, and so far have had no success.

ManueGE commented 7 years ago

Not sure I understand you, but I handled with a similar issue (I think) a few days ago.

I had a Entity User which has some attributes. In the responses from my api, I had an array of attributes which were different for each request, but they all belonged to the user so I didn't want them to replace the existing ones.

Finally I solved it by adding a custom accessor for my attributes relationship:

extension User {

    public var attributes: Set<Attribute>? {
        get {
            self.willAccessValue(forKey: #keyPath(User.attributes))
            let attributes = self.primitiveValue(forKey: #keyPath(User.attributes)) as? Set<Attribute>
            self.didAccessValue(forKey: #keyPath(User.attributes))
            return attributes
        }

        set {

            var set = Set<Attribute>()

            for attr in (attributes ?? []) {
                set.insert(attr)
            }

            for attr in (newValue ?? []) {
                set.insert(attr)
            }

            self.willChangeValue(forKey: #keyPath(User.attributes))
            self.setPrimitiveValue(set, forKey: #keyPath(User.attributes))
            self.didChangeValue(forKey: #keyPath(User.attributes))
        }
    }
}

Again, not sure if this is the problem you have, but maybe it could help.

Heia- commented 7 years ago

Thanks for the suggestion! I was able to use it to get something to work but not quite as generic/universal as I was hoping for.