Home > Net >  On delete cascade not working as intended in Gorm
On delete cascade not working as intended in Gorm

Time:08-26

So I am very new to Gorm and am playing around with it but I can't seem to get on delete cascade to work. These are my models:

type Base struct {
    Id string `json:"id" gorm:"type:uuid;primary_key"`
    CreatedAt time.Time `json:"created_at"`
    UpdatedAt time.Time `json:"updated_at"`
}

type User struct {
    Base
    Role     string  `json:"role"`
    Username string  `json:"username" gorm:"unique"`
    Password string  `json:"password"`
    Profile  Profile `gorm:"constraint:OnDelete:CASCADE;"`
}

type Profile struct {
    Base
    UserId string `json:"user_id"`
    Name   string `json:"name"`
    Bio    string `json:"bio" gorm:"default:hello world!"`
    Age    uint8  `json:"age"`
}

The problem is, when I perform a delete operation on a user object, it gets deleted properly but it's associated Profile object isn't deleted. I know that Gorm has a soft delete functionality but I don't have a gorm.DeletedAt field in my Base model. My User and Profile model also share the same Base so they should behave similarly in terms of the delete.

Here's how I am running the delete:

...
id := "my-uuid" // this would be a real value. this is just an example
Database.Where("id = ?", id).Delete(&models.User{})
...

What am I doing wrong?

Thank you!

Edit: I am aware of this question and have tried following it but I can't seem to get this to work.

CodePudding user response:

If you are using gorm v2, you can try deleting the main object, its relation, and the associated objects by using delete with select. It should be something like this:

Database.Select("Profile").Delete(&models.User{ID: id})

CodePudding user response:

you could use foreign key if your database support foreign key, if not you need use transaction to deleted the user and profile object.

https://gorm.io/docs/transactions.html

  • Related