This is the problem I am writing this code
result := db.Save(&emergency)
This error is because GORM needs to specify the WHERE condition when submitting the saved data to ensure that the database operation can be performed correctly. To fix this, try using Create
the method substitution Save
method while storing the result of the creation in a variable so you can check for errors.
In GORM, both Save
methods and Create
methods are used to save data to the database. Their main differences are:
save method
- usage:
db.Save(&data)
- Function: Perform insert or update operations based on the provided data object (structure). If the provided object already exists in the database (based on primary key or unique index), an update operation will be performed; otherwise, an insert operation will be performed.
- If the data object contains primary key or unique index fields, GORM will use these fields to decide whether to perform an insert or update operation.
- After performing the save operation,
Save
the method returns an*gorm.DB
object whoseError
properties can be used to check whether an error occurred.
Create method
- usage:
db.Create(&data)
- Function: Insert the provided data object into the database. It
Save
differs from the method in that it only performs inserts and does not attempt updates.Create
method ignores the primary key and unique index fields in the data object, and instead fills these fields with default values generated by the database (such as auto-increment IDs) or random values.- Similar to
Save
methods,Create
methods also return an*gorm.DB
object whoseError
properties you can use to check for errors.