Postgresql 删除约束上的Postgres外键
我一直在遵循关于尝试设置简单外键的指南,但是,我找不到有关在级联上使用Postgresql 删除约束上的Postgres外键,postgresql,go,go-gorm,Postgresql,Go,Go Gorm,我一直在遵循关于尝试设置简单外键的指南,但是,我找不到有关在级联上使用或在删除上使用的任何信息 在添加外键部分下,它确实使用了删除时的和级联时的,但是当我在插入时使用此方法时,会出现fk约束错误 我正在寻找关于使用第一种方法的建议,gorm:“foreignkey:userreference”,也可以在删除时指定,或者在级联时指定。有什么建议吗 编辑#1: 为了说明错误的含义,我将使用以下示例: 注意。开始: type Note struct { NoteId in
或在删除上使用的任何信息
在添加外键
部分下,它确实使用了删除时的和级联时的,但是当我在插入时使用此方法时,会出现fk约束错误
我正在寻找关于使用第一种方法的建议,gorm:“foreignkey:userreference”
,也可以在删除时指定,或者在级联时指定。有什么建议吗
编辑#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"`
}
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"`
}
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(¬e)
数据库。转到
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"`
}
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(¬e)
当将上述代码放入其适当的函数中时,将抛出此错误:
(pq: insert or update on table "notes" violates foreign key constraint "notes_recipient_id_users_user_id_foreign")
我也有同样的问题。
在您的案例中,当declare 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"`
}
同样在将来,如果您将删除或更新以下相关记录