Delete record
When deleting a record, it needs to have any conditions or it will raise error ErrMissingWhereClause
, for example:
e := query.Email |
Delete with primary key
GEN allows to delete objects using primary key(s) with inline condition, it works with numbers.
u.WithContext(ctx).Where(u.ID.In(1,2,3)).Delete() |
Batch Delete
The specified value has no primary value, GEN will perform a batch delete, it will delete all matched records
e := query.Email |
Soft Delete
If your model includes a gorm.DeletedAt
field (which is included in gorm.Model
), it will get soft delete ability automatically!
When calling Delete
, the record WON’T be removed from the database, but GORM will set the DeletedAt
‘s value to the current time, and the data is not findable with normal Query methods anymore.
// Batch Delete |
If you don’t want to include gorm.Model
, you can enable the soft delete feature like:
type User struct { |
Find soft deleted records
You can find soft deleted records with Unscoped
users, err := db.WithContext(ctx).Unscoped().Where(u.Age.Eq(20)).Find() |
Delete permanently
You can delete matched records permanently with Unscoped
o.WithContext(ctx).Unscoped().Where(o.ID.Eq(10)).Delete() |
Delete Associations
Remove the relationship between source & arguments if exists, only delete the reference, won’t delete those objects from DB.
u := query.User |
Delete with Select
You are allowed to delete selected has one/has many/many2many relations with Select
when deleting records, for example:
u := query.User |