Skip to content

Soft deletes

Radosław Mejer edited this page Oct 19, 2021 · 2 revisions

In addition to actually removing records from your database, Kex can also "soft delete" models. When models are soft deleted, they are not actually removed from your database. Instead, a deleted_at attribute is set on the model and inserted into the database. If a model has a non-null deleted_at value, the model has been soft deleted.

Enabling soft-deletes

const User = kex.createModel('User', {
  softDeletes: true
})

Usage

Soft-deleting a record

await User.query()
  .where('id', 1)
  .delete()

Force-remove a record

await User.query()
  .where('id', 1)
  .delete({ trash: false })

Fetching records

The soft-deletes plugin sets a soft-deletes global scope. This means, that all queries will exclude the soft-deleted records.

Fetch all records (including soft-deleted):

const usersList = await User.withTrashed()

Fetch only soft-deleted recrods:

const deletedUsers = await User.onlyTrashed()

Restoring the record

To "undelete" the record use the restore() method:

await User.withTrashed()
  .where('id', 1)
  .restore()

Configuration

You may change the name of the deleted column by passing an object with options:

  • columnName (optional; String; default: deleted_at)
Clone this wiki locally