Update handler for rest api /address/:id
func (s *Server) UpdateAddressByID(id int, updatedAddress *model.Address) error {
// Get the address by ID
var address model.Address
if err := s.DB.First(&address, id).Error; err != nil {
return err
}
// Update fields
address.Address = updatedAddress.Address
address.Address2 = updatedAddress.Address2
address.City = updatedAddress.City
address.Region = updatedAddress.Region
address.ZipCode = updatedAddress.ZipCode
address.Country = updatedAddress.Country
address.Updated_at = time.Now()
// Save the updated address
if err := s.DB.Save(&address).Error; err != nil {
return err
}
return nil
}
and If i call this function, api return error: address.go:179 WHERE conditions required
the line 179 is this if err := s.DB.Save(&address).Error; err != nil {
I am try put the where condition like this: if err := s.DB.Save(&address).where("address_id = ?", id).Error; err != nil {
but result was the same.
In Go language's GORM library, the
Savemethod is used to save the changes of a struct to the database. However, it's not used to specify conditions likeWHEREclauses. The error you're encountering, "WHERE conditions required," typically indicates that GORM expects a condition to be provided for the update operation.To resolve this, you need to make sure you are correctly specifying the
WHEREcondition when retrieving the address to update. Here's how you can modify yourUpdateAddressByIDfunction to include theWHEREcondition:Here, the
WHEREcondition is included in the query that retrieves the address to update. TheFirstmethod now contains the conditionWhere("id = ?", id), ensuring that only the address with the specifiedidis retrieved for updating. This should resolve the error you're encountering.