Reputation: 33
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
, CONSTRAINTfk_contents_category_model
FOREIGN KEY (cat_id
) REFERENCEScategories
(id
)) [3.247ms] [rows:0] INSERT INTOcontents
(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 ')
Upvotes: 1
Views: 326
Reputation: 625
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
Upvotes: 2