Approach for restoring vs creating with unique keys
mortocks opened this issue · comments
When using unique keys the the db you can't just call create() (Knex will throw errors due to duplicate entries) so you have to check if there is a previous record e.g.
const restored = Model.query().where('key', 'value')
if (!restored) {
// default adonis
Model.create({key: value})
} else {
// soft-deletes
restored.restore()
}
Are there plans to override the create() function like you do the delete() function to automate restoring or creating of models rather than having to perform this kind of check every time. If not, is there a more elegant solution than the example above to managing this situation?
Hey @mortocks , thanks for the question.
First of all, the query you posted does no include the soft-deleted entries. It should look like this:
const restored = Model.query().withTrashed().where('key', 'value')
Secondly, there's no plan to override the create()
method. Having this would require making additional query which would be an unnecessary performance hit.
If not, is there a more elegant solution than the example above to managing this situation?
I'm afraid this requires a context for your use-case. I can't recall a situation where I had to restore-or-create a new entry.
Narrowed to example you gave I'd recommend either keeping if/else
clause, or creating a macro which could handle similar cases.