Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftData @Query with #Predicate on Relationship Model

XCode 15 beta 6.

Just want to do a very simple Query Predicate where the relationship model matches:

@Query(
    filter: #Predicate<Piece> {
        $0.artist == selectedArtist
    },
    sort: [
        SortDescriptor(\Piece.age, order: .reverse)
    ]
) var pieces: [Piece]

and I'm receiving error:

Cannot convert value of type 'PredicateExpressions.Equal<PredicateExpressions.KeyPath<PredicateExpressions.Variable, Artist>, PredicateExpressions.Value>' to closure result type 'any StandardPredicateExpression'

I also tried .id and .persistentModelId on the artist but no luck.

This seems like the most basic predicate use case so I'd be shocked if it's not supported. Any ideas what i'm missing?

My models are basic:

@Model
final class Piece {
    var age: Int
    var artist: Artist
}

And

@Model
final class Artist {
    var name: String
    
    @Relationship(
        deleteRule: .cascade, 
        inverse: \Piece.artist
    )
    var pieces: [Piece]?
}
like image 479
William T. Avatar asked Sep 12 '25 03:09

William T.


1 Answers

You gave me an idea and it worked !!!

Considering that you can't use another model in the predicate, then first set a variable with the persistentModelID and use that variable in the predicate.

I was having the same problem and this worked for me. Of course you need to set the query in your init()

EDIT: I added part of the code that could be helpful.

@Query private var homes: [Home]

init(session: Session) {
    
    let id = session.persistentModelID
    let predicate = #Predicate<Home> { home in
        home.session?.persistentModelID == id
    }
    
    _homes = Query(filter: predicate, sort: [SortDescriptor(\.timestamp)] )
}
like image 190
Joel Avatar answered Sep 15 '25 07:09

Joel