TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SwiftData modelling question regarding to "find parent of child" in context of an 1:n relationship

Forums > SwiftUI

Hi team,

I playing around with SwiftData and I think i stumbled across of a few "why" questions during my journey. I really hope you can help me as a beginner out.

Models

ItemModel.swift

@Model class ItemModel {
    @Attribute(.unique)
    let id = UUID()

    let title: String
    ....

    @Relationship(deleteRule: .cascade)
    let images: [ImageModel]
}

ImageModel.swift

@Model class ImageModel {
    @Attribute(.unique)
    let id = UUID()

    @Relationship(inverse: \ItemModel.images)
    let parentItem: Item

    @Attribute(.externalStorage)
    let data: Data
}

My first idea (parent contains childs & child contains parent as property) Due to the fact, that the ItemModel contains a list and the ImageModel contains it's parent item, I should be able to display a list of images in the item detail view, and show the linked item in the image detail view.

A caviat of this could be, that I tightly bond ItemModel as a parent to the ImageModel, but maybe I will reuse the ImageModel to be a part of another parent like "CollectionModel" or something else.

Another issue with this approach is, that I need to make the images and the parent property a var because I need to create at first the item, than create the image with the newly created parent object in it.

Second idea (Query all of the parents to find the one who contains the image) Another approach would be to use a @Query to select the item which the images list contains the currently shown detail image id.

But this approach failed me hard. At first, I cannot use a let myProp value inside my #Predicate and it seems I cannot use any UUID typed properties to be my "WHERE foo.id == id" filters.

I'm confused I'm not really convinced that I'm on the right path in modeling all of this. It would be awesome if anyone of you could help me.

Happy christmas!

2      

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.

Learn more here

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.