首頁  >  文章  >  後端開發  >  GORM 無法更新一對​​多關係中的數據

GORM 無法更新一對​​多關係中的數據

PHPz
PHPz轉載
2024-02-10 18:00:101171瀏覽

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

php小編蘋果使用GORM框架時,可能會遇到一個常見問題:無法更新一對​​多關係中的資料。在一對多關係中,我們通常會有一個主表和一個從表,但是在進行更新操作時,GORM可能無法正確處理從表的資料更新。這個問題可能會導致資料不一致或更新失敗。在接下來的文章中,我們將詳細探討這個問題的解決方法,以幫助開發者更好地使用GORM框架。

問題內容

我有兩個表格使用者和文件。它們以這樣一種方式相關:每個文件必須屬於使用一對多關係的使用者。當我嘗試更新文件時出現以下錯誤

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

這是我的結構定義和更新函數

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)
}

解決方法

您正在呼叫Db.Save(&document)document 僅填入了其Name 字段。這意味著 UserID 設定為 0。我猜 User 表中不存在任何 ID 為 0 的用戶,因此這違反了外鍵約束。

更新文件時,UserID 欄位應始終設定為現有用戶,否則查詢將失敗。

不管怎樣,我建議你學習一些資料庫和golang基礎知識,因為你發布的程式碼相當混亂。

以上是GORM 無法更新一對​​多關係中的數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除