0

im pretty new on the SwiftUI so I dont how face this issue. Currently im creating expense app for my learning. Im still not understand how the model works. in this case I have 2 different model Transaction and Category


@Model
class TransactionModel{
    
    @Attribute(.unique) var id: String
    var amount: Float
    var creationDate: Date
    var notes: String
    @Relationship var categoryTrxs: CategoryModel?
    
    init(amount: Float, creationDate: Date, notes: String, categoryTrx: CategoryModel) {
        self.id = UUID().uuidString
        self.amount = amount
        self.creationDate = creationDate
        self.notes = notes
        self.categoryTrxs = categoryTrxs
    }
}

@Model
class CategoryModel{
    
    @Attribute(.unique)
    var id: String
    @Attribute(.transient)
    var isChecked = false
    var name: String
    var emoji: String
    var colors: String
    
    
    @Relationship(inverse: \TransactionModel.categoryTrxs)
    var trxs: [TransactionModel]?
    
    init(name: String, emoji: String, colors: String) {
        self.id = UUID().uuidString
        self.name = name
        self.emoji = emoji
        self.colors = colors

    }
    
}

This how I trying to save the transaction

@Environment(\.presentationMode) var presentationMode
@Environment (\.modelContext) private var context
@Query private var allCategory : [CategoryModel]
@Query private var allTrx: [TransactionModel]
 
@State private var isPopoverCategoryShows = false
@State private var selectedCategoryId = ""
@State private var amountString: String = "0"
@State private var date = Date()

.....

private var addTrxButton: some View{
    PrimaryButton(text: "Add") {
       
        var categoryGrabber: CategoryModel?

        // Find the selected category using its ID
        if let selectedCategory = allCategory.first(where: { $0.id == selectedCategoryId }) {
            categoryGrabber = selectedCategory
        }

        // Check if a category was found before creating the transaction
        if let category = categoryGrabber {
            let expenses = TransactionModel(amount: Float(amountString) ?? 0.0,
                                            creationDate: Date(),
                                            notes: "Test",
                                            categoryTrx: category)

            context.insert(expenses)
            
            do {
                try context.save()
                print("Transaction Added")
                print(expenses.categoryTrxs?.name ?? "None"," with Total amount ") // -> rendered as None 
                print(expenses.amount)  // -> rendered as correct amount 
                print(category.name) // -> rendered as correct category
            } catch {
                print(error.localizedDescription)
            }
        } else {
            print("Selected category not found.")
        }

            
    }
} 

The problem is when I tried to create a transaction/expense seems like the category is not attached to the Transaction. The expenses is added but the category is not there

enter image description here

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • 1
    You should [edit] your question so that it is fully contained rather than using external videos. Show the code where you are creating an expense and explain your problem – Paulw11 Jul 27 '23 at 10:24
  • Hi @Paulw11 apologize for the confusion I make an edit and add how I save/add the expense – Setyono Dwi Jul 27 '23 at 10:32
  • 1
    What is `allCategory`? Have you set a debugger breakpoint and verified that `if let selectedCategory = allCategory.first(where: ...` actually finds a category? – Paulw11 Jul 27 '23 at 11:07
  • yes I have query declaration for Category Mode and Transaction Model @ Query private var allCategory : [CategoryModel] @ Query private var allTrx: [TransactionModel] yess It did find the category that I selected. I have tried to print category.name and can see the result which is a category I selected. But I got no results when try do this print(expenses.categoryTrxs?.name ?? "None"," with Total amount ") – Setyono Dwi Jul 27 '23 at 12:43
  • I have make an edit for the question the query declaration and debugger on saving/adding the transaction hopes can get better idea – Setyono Dwi Jul 27 '23 at 12:48
  • 1
    [this answer](https://stackoverflow.com/questions/76606706/swiftdata-modeling-and-saving-non-nullable-relations/76608074#76608074) might be helpful – Joakim Danielson Jul 27 '23 at 14:12
  • 2
    thanks @JoakimDanielson yeah the answer that you share worked for me too – Setyono Dwi Jul 27 '23 at 14:47
  • Yes, so I tried to do the same which is to remove the properties with @relationship on Init and it just works for me! – Setyono Dwi Jul 28 '23 at 00:07

0 Answers0