Home >Backend Development >Golang >GORM cannot update data in one-to-many relationship

GORM cannot update data in one-to-many relationship

PHPz
PHPzforward
2024-02-10 18:00:101213browse

GORM 无法更新一对多关系中的数据

php editor Apple may encounter a common problem when using the GORM framework: data in a one-to-many relationship cannot be updated. In a one-to-many relationship, we usually have a master table and a slave table, but when performing update operations, GORM may not correctly handle data updates from the slave table. This problem may cause data inconsistency or update failure. In the next article, we will explore the solution to this problem in detail to help developers better use the GORM framework.

Question content

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

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

This is my structure 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)
}

Workaround

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

When updating a document, the UserID field should always be set to an existing user, otherwise the query will fail.

Anyway, I suggest you learn some database and golang basics, because the code you posted is quite confusing.

The above is the detailed content of GORM cannot update data in one-to-many relationship. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete