Delete Records
Phi provides two methods for deleting records:
DeleteDeleteMany
Note:
Deletealways returns the deleted record, regardless of the underlying database. On databases that supportDELETE ... RETURNING, Phi performs the deletion in a single query. On databases that don't, Phi transparently executes the operation inside a transaction by fetching the record before deleting it, ensuring consistent behavior across all supported SQL dialects.
Delete
Deletes a single record.
The first predicate must uniquely identify a record (for example, Id.EQ() or another unique field). Additional predicates may be supplied to further constrain the deletion.
By default, all scalar fields are returned. Use Select or Omit to customize the returned data.
Basic
user, err := db.User.Delete(
user.Email.EQ("x@y.com"),
).Exec(ctx)With Additional Predicates
user, err := db.User.Delete(
user.Email.EQ("x@y.com"),
user.Bio.Contains("golang"),
).Exec(ctx)Returning Selected Fields
user, err := db.User.Delete(
user.Id.EQ(id),
).
Select(user.Select{
Id: true,
Username: true,
}).
Exec(ctx)Omitting Fields
user, err := db.User.Delete(
user.Id.EQ(id),
).
Omit(user.Omit{
Password: true,
}).
Exec(ctx)Supported Builder Methods
| Method | Description |
|---|---|
Select |
Return only the selected fields and relations. |
Omit |
Return all scalar fields except the omitted ones. |
DeleteMany
Deletes all records matching the supplied predicates.
Unlike Delete, no unique predicate is required.
DeleteMany returns the number of rows deleted.
Basic
deleted, err := db.User.DeleteMany(
user.Bio.Contains("inactive"),
).Exec(ctx)Multiple Predicates
deleted, err := db.User.DeleteMany(
user.Email.HasSuffix("@example.com"),
user.LoginCount.LT(5),
).Exec(ctx)Using Logical Predicates
deleted, err := db.User.DeleteMany(
user.Or(
user.Bio.Contains("spam"),
user.PhoneNum.HasPrefix("+999"),
),
).Exec(ctx)Return Value
deleted, err := db.User.DeleteMany(
user.Bio.Contains("inactive"),
).Exec(ctx)
fmt.Printf("Deleted %d users\n", deleted)Supported Builder Methods
DeleteMany exposes no additional builder methods beyond its predicates.
Note:
DeleteManyonly returns the number of deleted rows. If you need the deleted records themselves, query them before deleting.