在删除约束上发布外键



一直按照指南尝试设置简单的外键 http://gorm.io/docs/belongs_to.html,但是,我找不到有关使用ON CASCADEON DELETE的任何信息。

Add Foreign Key部分下的 http://doc.gorm.io/database.html#migration,它确实使用了ON DELETEON CASCADE,但是当我在插入时使用此方法时,我得到一个fk约束错误。

我正在寻找有关使用第一种方法的建议,gorm:"foreignkey:UserRefer",也指定ON DELETEON CASCADE。有什么建议吗?

编辑#1: 为了说明我所说的错误是什么意思,我将以此为例:

注意去:

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"`
}

用户.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"`
}

数据库.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:"test@gmail.com"}
note := models.Note{RecipientId:user.UserId, Content:"test"}
db.Create(&user)
db.Create(&note)

当上面的代码放在其正确的函数中时,会抛出此错误:

(pq: insert or update on table "notes" violates foreign key constraint "notes_recipient_id_users_user_id_foreign") 

我也有同样的问题。 在您的情况下声明结构时,最好设置一个外键:

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:是否可以通过多2多关系删除记录?

最新更新