【问题标题】:GORM unable to update data in one to many relationshipGORM 无法更新一对多关系中的数据
【发布时间】:2023-01-03 23:01:16
【问题描述】:

我有两个表用户和文件。它们以这样一种方式相关,即每个文档必须属于使用一对多关系的用户。当我尝试更新文档时出现以下错误

错误:插入或更新表“文档”违反了外键 约束“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)
}

【问题讨论】:

    标签: postgresql go grails-orm


    【解决方案1】:

    您正在呼叫 Db.Save(&document),但 document 仅填充了其 Name 字段。这意味着 UserID 设置为 0。我猜您在 User 表中没有任何 ID 为 0 的用户,因此这违反了外键约束。

    更新文档时,UserID 字段应始终设置为现有用户,否则查询将失败。

    无论如何,我建议您学习一些数据库和 golang 基础知识,因为您发布的代码非常混乱。

    【讨论】:

      猜你喜欢
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2018-09-26
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      • 2019-12-11
      相关资源
      最近更新 更多