// Delete by ID err := gorm.G[Email](db).Where("id = ?", 10).Delete(ctx) // DELETE from emails where id = 10;
// Delete with additional conditions err := gorm.G[Email](db).Where("id = ? AND name = ?", 10, "jinzhu").Delete(ctx) // DELETE from emails where id = 10 AND name = "jinzhu";
Traditional API
// Email's ID is `10` db.Delete(&email) // DELETE from emails where id = 10;
// Delete with additional conditions db.Where("name = ?", "jinzhu").Delete(&email) // DELETE from emails where id = 10 AND name = "jinzhu";
func(u *User) BeforeDelete(tx *gorm.DB) (err error) { if u.Role == "admin" { return errors.New("admin user not allowed to delete") } return }
一括削除
主キーが指定されていない場合、GORMは指定された条件にマッチしたレコードの一括削除を実行します。
Generics API
ctx := context.Background()
// Batch delete with conditions err := gorm.G[Email](db).Where("email LIKE ?", "%jinzhu%").Delete(ctx) // DELETE from emails where email LIKE "%jinzhu%";
Traditional API
db.Where("email LIKE ?", "%jinzhu%").Delete(&Email{}) // DELETE from emails where email LIKE "%jinzhu%";
db.Delete(&Email{}, "email LIKE ?", "%jinzhu%") // DELETE from emails where email LIKE "%jinzhu%";
INFO DeletedAt フィールドに一意の複合インデックスを作成するには、gorm.io/plugin/soft_delete プラグインのヘルパーによるUNIX秒/フラグといった、ほかのデータ形式を使用しなければなりません。
import"gorm.io/plugin/soft_delete"
type User struct { ID uint Name string`gorm:"uniqueIndex:udx_name"` DeletedAt soft_delete.DeletedAt `gorm:"uniqueIndex:udx_name"` }
UNIX秒
UNIX秒を削除フラグとして使用
import"gorm.io/plugin/soft_delete"
type User struct { ID uint Name string DeletedAt soft_delete.DeletedAt }
// Query SELECT * FROM users WHERE deleted_at = 0;
// Delete UPDATE users SET deleted_at = /* current unix second */ WHERE ID = 1;
ミリ秒 milli またはナノ秒 nano を値として指定することもできます。例:
type User struct { ID uint Name string DeletedAt soft_delete.DeletedAt `gorm:"softDelete:milli"` // DeletedAt soft_delete.DeletedAt `gorm:"softDelete:nano"` }
// Query SELECT * FROM users WHERE deleted_at = 0;
// Delete UPDATE users SET deleted_at = /* current unix milli second or nano second */ WHERE ID = 1;
1 / 0 を削除フラグとして使用
import"gorm.io/plugin/soft_delete"
type User struct { ID uint Name string IsDel soft_delete.DeletedAt `gorm:"softDelete:flag"` }
// Query SELECT * FROM users WHERE is_del = 0;
// Delete UPDATE users SET is_del = 1 WHERE ID = 1;
type User struct { ID uint Name string DeletedAt time.Time IsDel soft_delete.DeletedAt `gorm:"softDelete:flag,DeletedAtField:DeletedAt"`// use `1` `0` // IsDel soft_delete.DeletedAt `gorm:"softDelete:,DeletedAtField:DeletedAt"` // use `unix second` // IsDel soft_delete.DeletedAt `gorm:"softDelete:nano,DeletedAtField:DeletedAt"` // use `unix nano second` }
// Query SELECT * FROM users WHERE is_del = 0;
// Delete UPDATE users SET is_del = 1, deleted_at = /* current unix second */ WHERE ID = 1;