UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SwiftData Filter by object and relationship?

Forums > SwiftUI

I have two Model classes: List and ListItem that are related where List is the parent. The ListItem model has 2 objects: name and type.

I have a screen that I want to display items from a specific list grouped by type. Since (as far as my research has shown) SwiftData can't do a simple GROUP BY, I need 6 different variables (one for each type) and then 6 different ForEach statements with the same UI code inside, one for each variable (why? why? but ok).

Where I'm stuck is writing a predicate based on a parent field. I'm passing in the list from the prior View so I tried this:


 @State var list: List

    @Query(filter: #Predicate<ListItem> { item in
        item.list == list && item.type == "Clothing"
    }) var clothing: [ListItem]

The error I get says that list cannot be used on type 'ListView'. Is there a way to filter by the parent related item and an object in the model at the same time?

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.