go lang rest api return WHERE conditions required

186 Views Asked by At

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.

1

There are 1 best solutions below

0
sk shahriar ahmed raka On

In Go language's GORM library, the Save method is used to save the changes of a struct to the database. However, it's not used to specify conditions like WHERE clauses. 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 WHERE condition when retrieving the address to update. Here's how you can modify your UpdateAddressByID function to include the WHERE condition:

func (s *Server) UpdateAddressByID(id int, updatedAddress *model.Address) error {
    // Get the address by ID
    var address model.Address
    if err := s.DB.Where("id = ?", id).First(&address).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
}

Here, the WHERE condition is included in the query that retrieves the address to update. The First method now contains the condition Where("id = ?", id), ensuring that only the address with the specified id is retrieved for updating. This should resolve the error you're encountering.