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

huangapple go评论80阅读模式
英文:

GORM unable to update data in one to many relationship

问题

我有两个表,用户(users)和文档(documents)。它们之间的关系是每个文档必须属于一个用户,使用一对多的关系。当我尝试更新一个文档时,出现以下错误:

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

// 根据ID更新文档
func (h handler) UpdateDocument(w http.ResponseWriter, r *http.Request) {

    // 首先,我们需要解析路径参数
    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)
}

希望这能帮到你!

英文:

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

答案1

得分: 1

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

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

不管怎样,我建议你学习一些数据库和Golang的基础知识,因为你发布的代码相当混乱。

英文:

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.

huangapple
  • 本文由 发表于 2023年1月3日 21:56:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/74994349.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定