ios – SwiftData filtering on a one-to-many relationship that has a many to many relationship


So the title is a bit confusing didn’t know how to word it. Besides that here is the problem I am facing. I am trying to filter on a many to many relationship. For simplicity here is how my models look like.

@Model
class Object1 {
    @Attribute(.unique) var name: String
    var object2: Object2?
    init(
        name: String
    ) {
        self.name = name
    }
}

@Model
class Object2 {
    @Attribute(.unique) var name: String
    var objects1: [Object1]?
    @Relationship(inverse: \Object3.objects2) var objects3: [Object3]?
    
    init(
        name: String
    ) {
        self.name = name
    }
}

@Model
class Object3 {
    @Attribute(.unique) var name: String
    var objects2: [Object2]?
    
    init(
        name: String
    ) {
        self.name = name
    }
}

So Object 1 has a one-to-many relationship with Object2. Now Object2 has a many-to-many relationship with object3. I am trying to filter by making my query look something like this.

@Query var objects1: [Object1]

init(sortDescriptors: [SortDescriptor]) {
    
    _objects1 = Query(
        filter: #Predicate { object1 in
            return object1.object2?.objects3?.contains { $0.name == "name" } ?? false
        },
        sort: sortDescriptors
    )

Now doing this gives me this error.

error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x6000038007e0> , to-many key not allowed here with userInfo of (null)
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here'

I have watch some videos on SwiftData but didn’t come across anything relating to this. I can’t ask ChatGPT cause it has no knowledge on this. Can’t really find anything for SwiftData but found something similar on CoreData but they use NSPredicate not sure how to use that in SwiftData #Predicate?

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img