Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zahidmuhammadzaki/9c1cfc30323d22e8fd0a240a6e52c140 to your computer and use it in GitHub Desktop.
Save zahidmuhammadzaki/9c1cfc30323d22e8fd0a240a6e52c140 to your computer and use it in GitHub Desktop.
Soft delete trait for Adonis 4.
// $ 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