-
-
Save zahidmuhammadzaki/9c1cfc30323d22e8fd0a240a6e52c140 to your computer and use it in GitHub Desktop.
Soft delete trait for Adonis 4.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// $ adonis make:trait SoftDelete | |
class SoftDelete { | |
register (Model, customOptions = {}) { | |
const deletedAtColumn = customOptions.name || `${Model.table}.deleted_at`; | |
Model.addGlobalScope(builder => { | |
builder.whereNull(deletedAtColumn); | |
}, 'soft_delete'); | |
Model.queryMacro('withTrashed', function () { | |
this.ignoreScopes(['soft_delete']); | |
return this; | |
}); | |
Model.queryMacro('onlyTrashed', function () { | |
this.ignoreScopes(['soft_delete']); | |
this.whereNotNull(deletedAtColumn); | |
return this; | |
}); | |
Model.prototype.delete = async () => { | |
this[deletedAtColumn] = new Date(); | |
await this.save(); | |
}; | |
Model.prototype.restore = async () => { | |
this[deletedAtColumn] = null; | |
await this.save(); | |
}; | |
Model.prototype.forceDelete = async () => { | |
await Model.query() | |
.where(Model.primaryKey, this[Model.primaryKey]) | |
.ignoreScopes() | |
.delete(); | |
}; | |
} | |
} | |
module.exports = SoftDelete |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment