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