Home > front end >  GORM unable to update data in one to many relationship
GORM unable to update data in one to many relationship

Time:01-05

I have two tables users and documents. They are related in such a way that each document must belong to a user using a one to many relationship. When I try updating a document I get the following error

ERROR: insert or update on table "documents" violates foreign key constraint "fk_users_documents" (SQLSTATE 23503)

Here are my structs definition and update function

type User struct {
    gorm.Model
    Name      string
    Email     string
    Password  string
    Documents []Document 
}

type Document struct {
    gorm.Model
    Name   string
    UserID uint
}




//Update document by id
func (h handler)UpdateDocument(w http.ResponseWriter, r *http.Request) {

    // once again, we will need to parse the path parameters
    var updatedDoc Document
    reqBody, _ := ioutil.ReadAll(r.Body)
    json.Unmarshal(reqBody, &updatedDoc)
    var document Document
    vars := mux.Vars(r)
    id := vars["id"]


    
    
    if result := Db.First(&updatedDoc, id); result.Error != nil {
        fmt.Println(result.Error)
    }

    document.Name=updatedDoc.Name

    
    Db.Save(&document)
    json.NewEncoder(w).Encode(&updatedDoc)
}

CodePudding user response:

You are calling Db.Save(&document) but document has only its Name field populated. This means that the UserID is set to 0. I'm guessing you don't have any user with ID 0 present in the User table, therefore this violates the foreign key constraint.

The UserID field shall always be set to an existing user when updating a document otherwise the query will fail.

Regardless of this, I'd suggest you to study a bit of database and golang basics because the code you posted is quite messy.

  • Related