1

When I try to insert to a table with gorm which has one to many relationship, I get this error:

Error 1452: Cannot add or update a child row: a foreign key constraint fails (`Todo`.`todos`, CONSTRAINT `fk_users_todo_list` FOREIGN KEY (`fk_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE).... 

These are my models:

type Base struct { ID uint `gorm:"primaryKey"` CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time `gorm:"index"` } type User struct { Base FirstName string `form:"first_name" gorm:"type:varchar(20)"` LastName string `form:"last_name" gorm:"type:varchar(20)"` UserName string `form:"user_name" gorm:"unique;type:varchar(20)"` Email string `form:"email" gorm:"type:varchar(100)"` Password string `form:"password" gorm:"type:varchar(30)"` Gender types.UserGender `form:"gender" gorm:"type:smallint"` TodoList []Todo `gorm:"foreignKey:FkID;constraint:onDelete:SET NULL,onUpdate:CASCADE" json:"omitempty"` } type Todo struct { Base Name string Description string Status types.TaskStatus FkID uint } 

And this is the function that I wrote:

func (d *DB) AddTODO(todo *models.Todo, userName string) error { user := &models.User{UserName: userName} err := d.db.Model(&user).Where("user_name = ?", userName).Association("TodoList"). Append([]models.Todo{*todo}) if err != nil { return err } return nil } 

I'm using MariaDB.

2 Answers 2

1

It want user from gorm result. Change your method maybe like this:

// arg user is from gorm result somewhere func (d *DB) AddTODO(user *models.User, todo *models.Todo) error { return d.db.Model(user).Association("TodoList").Append([]models.Todo{*todo}) } 
Sign up to request clarification or add additional context in comments.

7 Comments

i created a user and it's okay when i try to access it with mysql or goland query console or with gorm, and when i write query like you it throw this error: WHERE conditions required [0.364ms] [rows:0] UPDATE `users` SET `updated_at`='2022-03-03 12:27:37.347'
I think it want a user from gorm result, like this example, sourcegraph.com/github.com/jinzhu/gorm/-/blob/… see line 601 and line 620
thnak you ! i tried to get user's full info and then create a todo and it's working!
OK, I'll edit my answer above
Btw you forgot to get the Error, see my edited answer.
|
0

TodoList lack references keyword. It should be like this.

type User struct { Base FirstName string `form:"first_name" gorm:"type:varchar(20)"` LastName string `form:"last_name" gorm:"type:varchar(20)"` UserName string `form:"user_name" gorm:"unique;type:varchar(20)"` Email string `form:"email" gorm:"type:varchar(100)"` Password string `form:"password" gorm:"type:varchar(30)"` Gender types.UserGender `form:"gender" gorm:"type:smallint"` TodoList []Todo `gorm:"foreignKey:FkID;references:ID;constraint:onDelete:SET NULL,onUpdate:CASCADE" json:"omitempty"` } 

1 Comment

i tried it and its same Error 1452: Cannot add or update a child row: a foreign key constraint fails (`Todo`.`todos`, CONSTRAINT `fk_users_todo_list` FOREIGN KEY (`fk_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE) [1.267ms] [rows:0] INSERT INTO `todos` (`created_at`,`updated_at`,`deleted_at`,`name`,`description`,`status`,`fk_id`) VALUES ('2022-03-03 12:17:38.649','2022-03-03 12:17:38.649',NULL,'my first todo','Test description','2',0) ON DUPLICATE KEY UPDATE `fk_id`=VALUES(`fk_id`) this is the full error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.