[按照http://gorm.io/docs/belongs_to.html指南尝试进行简单的外键设置,但是,我找不到有关使用ON CASCADE
或ON DELETE
的任何信息。
在http://doc.gorm.io/database.html#migration部分下的Add Foreign Key
上,它的确使用了ON DELETE
和ON CASCADE
,但是当我在插入时使用此方法时,出现fk约束错误。
我正在寻找有关使用第一种方法gorm:"foreignkey:UserRefer"
的建议,以同时指定ON DELETE
或ON CASCADE
。有什么建议吗?
编辑#1:为了显示我的错误意思,我将使用它作为示例:
Note.go:
type Note struct {
NoteId int `gorm:"primary_key;AUTO_INCREMENT"`
RecipientId int `gorm:"index"`
Content string `gorm:"not null"`
CreatedAt time.Time `gorm:"not null"`
UpdatedAt time.Time `gorm:"not null"`
}
User.go
type User struct {
UserId int `gorm:"primary_key;AUTO_INCREMENT"`
Username string `gorm:"not null;unique"`
Email string `gorm:"not null;unique"`
Notes []Note
CreatedAt time.Time `gorm:"not null"`
UpdatedAt time.Time `gorm:"not null"`
}
database.go
db.AutoMigrate(&models.User{}, &models.Note{})
db.Model(&models.Note{}).AddForeignKey("recipient_id", "users(user_id)", "RESTRICT", "RESTRICT")
user := models.User{Username:"test", Email:"[email protected]"}
note := models.Note{RecipientId:user.UserId, Content:"test"}
db.Create(&user)
db.Create(¬e)
当以上代码置于其适当的功能中时,会引发此错误:
(pq: insert or update on table "notes" violates foreign key constraint "notes_recipient_id_users_user_id_foreign")
我也有同样的问题。最好在您的情况下声明struct时设置一个外键:
type Note struct {
NoteId int `gorm:"primary_key;AUTO_INCREMENT"`
RecipientId int `gorm:"recipient_id"`// your variant `gorm:"index"`
Content string `gorm:"not null"`
CreatedAt time.Time `gorm:"not null"`
UpdatedAt time.Time `gorm:"not null"`
}
type User struct {
UserId int `gorm:"primary_key;AUTO_INCREMENT"`
Username string `gorm:"not null;unique"`
Email string `gorm:"not null;unique"`
Notes []Note `gorm:"foreignkey:recipient_id"`
CreatedAt time.Time `gorm:"not null"`
UpdatedAt time.Time `gorm:"not null"`
}
也将来,如果您要删除或更新此Golang Gorm: Is it possible to delete a record via a many2many relationship?之后的相关记录,则>