Skip to content

Instantly share code, notes, and snippets.

@andresilvagomez
Last active August 3, 2023 18:08
Show Gist options
  • Save andresilvagomez/87f6f9a95387679dc9f963b3aa061358 to your computer and use it in GitHub Desktop.
Save andresilvagomez/87f6f9a95387679dc9f963b3aa061358 to your computer and use it in GitHub Desktop.
Soft deletes for Adonis 4.
// $ adonis make:trait SoftDeletes
class SoftDeletes {
register(Model, customOptions = {}) {
const deletedAtColumn = customOptions.name || `${Model.table}.deleted_at`;
Model.addGlobalScope(builder => {
builder.whereNull(deletedAtColumn);
}, 'adonis_soft_deletes');
Model.queryMacro('withTrashed', () => {
this.ignoreScopes('adonis_soft_deletes');
return this;
});
Model.queryMacro('onlyTrashed', () => {
this.ignoreScopes('adonis_soft_deletes');
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 = SoftDeletes;
@JonhnyDev
Copy link

JonhnyDev commented Mar 9, 2022

It only works when you first search for the value and then delete it, if you do as the query below does not work.
"Bulk Deletes"

work:
let get = await Test_Softdelete.query().where('value', 10).first() if(get){ await get.delete() return get }
doesn't work with an array of data like fetch.
dont working:
await Test_Softdelete.query().where('value', 10).delete()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment