Reputation: 1084
Been following the guide on http://gorm.io/docs/belongs_to.html trying to get simple foreign keys setup, however, I can't find any info on using ON CASCADE
or ON DELETE
.
On http://doc.gorm.io/database.html#migration under the Add Foreign Key
section it does make use of ON DELETE
and ON CASCADE
, however when I use this method when inserting I get a fk constraint error.
I'm looking for advice on using the first method ,gorm:"foreignkey:UserRefer"
, to also specify ON DELETE
or ON CASCADE
. Any suggestions?
EDIT #1: To show what I mean by error, I'll use this as an example:
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)
When the above code is placed in its proper functions, this error is thrown:
(pq: insert or update on table "notes" violates foreign key constraint "notes_recipient_id_users_user_id_foreign")
Upvotes: 1
Views: 1660
Reputation: 155
I have the same issue too. The good idea is set a foreign keys when declare struct in your case is:
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"`
}
Also in the future, if you will delete or update related records folow this Golang Gorm: Is it possible to delete a record via a many2many relationship?
Upvotes: 1