How can I add a default where clause to all queries for certain models?

Viewed 251

Is there a way to add a certain where clause by default to certain models in Objection?

Context

Some of my Objection models use "soft deletes" - rather than actually deleting them from the database, their deleted_at column is marked with a timestamp.

By default I'd like to ensure that where deleted_at is null is included by default in all my queries so that I don't have to remember to add that in manually.

Is there a way to do this in Objection or Knex?

1 Answers

You can overwrite the query method in your Model:

class SoftDeleteModel extends Model {
    static query(...args) {
        return super.query(...args).where('deleted_at', null)
    }
}

super.query refers to the "original" / parent's Objection query method.

Related