当前位置: 首页 > 文档资料 > Sequelize ORM 实践 >

第五章 查询范围 Scope (预定义查询条件)

优质
小牛编辑
118浏览
2023-12-01

可不可以有一种方式提前定义好 where 条件,然后将这种定义好的条件又可以重新组合呢?答案就是 Scope

const Project = sequelize.define('project', {
  // Attributes
}, {
  defaultScope: {
    where: {
      active: true
    }
  },
  scopes: {
    deleted: {
      where: {
        deleted: true
      }
    },
    activeUsers: {
      include: [
        { model: User, where: { active: true }}
      ]
    },
    random: function () {
      return {
        where: {
          someNumber: Math.random()
        }
      }
    },
    accessLevel: function (value) {
      return {
        where: {
          accessLevel: {
            $gte: value
          }
        }
      }
    }
  }
});

在这个例子中,defaultScope 就是默认的条件,也就是说当 Project 在使用查询的时候,会自动把该配置项下面的选项加到语句中。

如下:

SELECT * FROM projects WHERE active = true

而 scopes 里面定义的,我们可以通过模型的 scope 方法来指定使用哪一个范围。并且可以通过 unscoped 方法与scope(null) 可以移除默认的 scope。

例如:

Project.scope('deleted').findAll();

就会移除默认的 defaultScope

scope 传入参数

当我们 scopes 里面定义的是函数的时候,可以传入函数参数,具体如何传入如下:

Project.scope('random', { method: ['accessLevel', 19]}).findAll();

socope 的组合

当使用 scope 的时候会移除默认的 defaultScope,可以手动加上defaultScope

Project.scope('defaultScope', 'deleted').findAll();
Project.scope(['deleted', 'activeUsers']).findAll();

而对于模型关系的 scope 在模型关系定义里面以及说得非常清楚了,这里就不再进行赘述。