Postgres外键上的删除约束

问题描述 投票:1回答:1

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

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

我正在寻找有关使用第一种方法gorm:"foreignkey:UserRefer"的建议,以同时指定ON DELETEON 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(&note)

当以上代码置于其适当的功能中时,会引发此错误:

(pq: insert or update on table "notes" violates foreign key constraint "notes_recipient_id_users_user_id_foreign") 
postgresql go go-gorm
1个回答
1
投票

我也有同样的问题。最好在您的情况下声明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?之后的相关记录,则>

© www.soinside.com 2019 - 2024. All rights reserved.