【问题标题】:How can I add a default where clause to all queries for certain models?如何为某些模型的所有查询添加默认 where 子句?
【发布时间】:2021-10-07 15:49:28
【问题描述】:

有没有办法在Objection中的某些模型中默认添加某个where子句?

上下文

我的一些 Objection 模型使用“软删除”——而不是实际从数据库中删除它们,它们的 deleted_at 列标有时间戳。

默认情况下,我想确保在我的所有查询中默认包含where deleted_at is null,这样我就不必记住手动添加它。

有没有办法在 Objection 或 Knex 中做到这一点?

【问题讨论】:

    标签: knex.js objection.js


    【解决方案1】:

    您可以覆盖模型中的query 方法:

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

    super.query 指的是“原始”/父母的反对query 方法。

    【讨论】:

    • 这正是我想要的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-01-01
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    相关资源
    最近更新 更多