Last active
August 3, 2023 18:08
-
-
Save andresilvagomez/87f6f9a95387679dc9f963b3aa061358 to your computer and use it in GitHub Desktop.
Soft deletes 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 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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()