so I have 2 tables in a zero-to-many relation. (Each File can have at most 1 User).
type User struct {
gorm.Model
}
and
type File struct {
gorm.Model
UserID int `gorm:"default:null"`
User User `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;foreignKey:UserID"`
}
Now, in MySQL (this problem doesn't occur with SQLite), I get the following error if there is no user created and I update a file with an empty user:
Error 1452: Cannot add or update a child row: a foreign key constraint fails (`DB`.`files`, CONSTRAINT `fk_files_creator` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE SET NULL ON UPDATE CASCADE)
UPDATE `files` SET `user_id`=0,`deleted_at`=NULL WHERE `id` = 5
This is cause it is trying to add "0" as user_id when it should be NULL. Like this:
UPDATE `files` SET `user_id`=NULL,`deleted_at`=NULL WHERE `id` = 5
I managed to fix that for creating using default:null, but any idea how to do it for updating as well? Thanks!