Postgres外键上的删除约束

时间:2018-06-19 17:30:36

标签: postgresql go go-gorm

在遵循http://gorm.io/docs/belongs_to.html指南之后,尝试进行简单的外键设置,但是,我找不到有关使用df1 = df1[~df1['MatchId'].isin(df1.loc[df1.Home_Goal_Time >= 200, 'MatchId'])] ON CASCADE的任何信息。

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

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

编辑#1: 为了显示我的错误意思,我将使用它作为示例:

Note.go:

ON CASCADE

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

database.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(&note)

1 个答案:

答案 0 :(得分: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?

之后的相关记录,