错误 1452:无法添加或更新子行(GOLANG 和 MYSQL)

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

Error 1452: Cannot add or update a child row (GOLANG AND MYSQL)

问题

我是你的中文翻译助手,以下是你提供的代码的翻译:

我是一个 Golang 实习生。我在使用 GORM 时遇到了一个使用外键的问题。我正在尝试编写一个 CRUD 操作。我在使用 GORM 时,当使用外键时出现了错误:Error 1452: 无法添加或更新子行。

package migrations

import "gorm.io/gorm"

type Category struct {
   gorm.Model
   ID    uint
   Title string `gorm:"type:varchar(255)"`
   Sort  int
}
package migrations

import "gorm.io/gorm"

type Contents struct {
   gorm.Model
   ID            uint
   CategoryModel Category `gorm:"foreignKey:cat_id"`
   CatId         uint
   Title         string `gorm:"type:varchar(255)"`
   Content       string `gorm:"content,type:varchar(255)"`
}

我得到了以下错误信息:

2022/11/23 14:31:33 /home/channelead/Documents/blog-service-go/internal/activities/blog/Contents/action.go:26 Error 1452: Cannot add or update a child row: a foreign key constraint fails

(service-blog-go.contents, CONSTRAINT fk_contents_category_model FOREIGN KEY (cat_id) REFERENCES categories (id))
[3.247ms] [rows:0] INSERT INTO contents (created_at,updated_at,deleted_at,cat_id,title,content) VALUES ('2022-11-23 14:31:33.972','2022-11-23 14:31:33.972',NULL,0,'khodaya csacas dg','testing ')

英文:

im a golang intern .I have a problem using foreign keys in gorm. im trying to write a crud operation.im using gorm and when using foreign keys the error : Error 1452: Cannot add or update a child row appears.

package migrations

import "gorm.io/gorm"

type Category struct {
   gorm.Model
   ID    uint
   Title string `gorm:"type:varchar(255)"`
   Sort  int
}

package migrations

import "gorm.io/gorm"

type Contents struct {
   gorm.Model
   ID            uint
   CategoryModel Category `gorm:"foreignKey:cat_id"`
   CatId         uint
   Title         string `gorm:"type:varchar(255)"`
   Content       string `gorm:"content,type:varchar(255)"`
}

and i got this error :

> 2022/11/23 14:31:33 /home/channelead/Documents/blog-service-go/internal/activities/blog/Contents/action.go:26 Error 1452: Cannot add or update a child row: a foreign key constraint fails
>
> (service-blog-go.contents, CONSTRAINT fk_contents_category_model FOREIGN KEY (cat_id) REFERENCES categories (id))
[3.247ms] [rows:0] INSERT INTO contents (created_at,updated_at,deleted_at,cat_id,title,content) VALUES ('2022-11-23 14:31:33.972','2022-11-23 14:31:33.972',NULL,0,'khodaya csacas dg','testing ')

答案1

得分: 2

请注意插入查询。您将0作为cat_id给出,它引用了Category表中的ID。但是,在Category表中没有ID为0的条目。另一个重要的事实是,如果使用gorm.Model,您不需要显式地使用ID,因为它已经在其中有一个ID字段。并且CategoryModel字段应该重命名为Category。这些是gorm的默认设置,但您可以配置这些内容。请阅读文档。这是工作代码GITHUB链接。您可以克隆该存储库并运行。

package storage

import (
	"fmt"
	"log"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type Category struct {
	gorm.Model
	Title string `gorm:"type:varchar(255)"`
	Sort  int
}

type Contents struct {
	gorm.Model
	Category   Category
	CategoryID uint
	Title      string `gorm:"type:varchar(255)"`
	Content    string `gorm:"type:varchar(255)"`
}

func GormTest3() {
	db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		log.Fatal("无法打开数据库")
	}
	err = db.AutoMigrate(&Contents{}, &Category{})
	if err != nil {
		log.Fatal("无法迁移数据库")
	}
	createTestData3(db)
	fetchData3(db)
}

func createTestData3(db *gorm.DB) {
	category := Category{
		Title: "ABC",
		Sort:  1,
	}
	err := db.Create(&category).Error
	if err != nil {
		fmt.Println("无法创建用户数据")
	}

	content := Contents{
		CategoryID: category.ID,
		Title:      "Good Content Title",
		Content:    "Good Content",
	}

	err = db.Create(&content).Error
	if err != nil {
		fmt.Println("无法创建用户数据")
	}
}

func fetchData3(db *gorm.DB) {
	var cts []Contents
	if err := db.Find(&cts).Error; err != nil {
		fmt.Println("无法加载帖子")
	}
	fmt.Println(cts)
}

参考:Gorm Has One

英文:

Please notice the insert query. You are giving 0 as cat_id which reference the ID of Category table. But there is no entry with 0 ID in Category table. Another important fact is you don’t need ID explicitly if you use gorm.Model because it has a ID field inside. And CategoryModel field should be renamed to Category. These are gorm default but you can configure these things. Please read the documentation. Here is the working code GITHUB LINK. You can clone the repo and run.

package storage
import (
"fmt"
"log"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
type Category struct {
gorm.Model
Title string `gorm:"type:varchar(255)"`
Sort  int
}
type Contents struct {
gorm.Model
Category   Category
CategoryID uint
Title      string `gorm:"type:varchar(255)"`
Content    string `gorm:"type:varchar(255)"`
}
func GormTest3() {
db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
log.Fatal("could not open database")
}
err = db.AutoMigrate(&Contents{}, &Category{})
if err != nil {
log.Fatal("could not migrate database")
}
createTestData3(db)
fetchData3(db)
}
func createTestData3(db *gorm.DB) {
category := Category{
Title: "ABC",
Sort:  1,
}
err := db.Create(&category).Error
if err != nil {
fmt.Println("failed to create user data")
}
content := Contents{
CategoryID: category.ID,
Title:      "Good Content Title",
Content:    "Good Content",
}
err = db.Create(&content).Error
if err != nil {
fmt.Println("failed to create user data")
}
}
func fetchData3(db *gorm.DB) {
var cts []Contents
if err := db.Find(&cts).Error; err != nil {
fmt.Println("failed to load post")
}
fmt.Println(cts)
}

Ref: Gorm Has One

huangapple
  • 本文由 发表于 2022年11月23日 19:02:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/74545752.html
匿名

发表评论

匿名网友

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

确定