Sequelize
  • Introduction
  • 写在前面的话
  • 第一章 搭建环境
  • 第二章 模型定义
    • 2.1 实例变量方法
    • 2.2 定义一个模型
    • 2.3 模型字段类型
    • 2.3 导入与配置
  • 第三章 模型关系
    • 3.1 属于
    • 3.2 包含
    • 3.3 一对多
    • 3.4 多对多
    • 3.5 多态一对多
    • 3.6 多态多对多
    • 3.7 关系嵌套
  • 第四章 模型查询
  • 第五章 查询范围 Scope (预定义查询条件)
  • 第六章 生命周期函数 Hook
  • 第七章 数据库迁移 Migrate
  • 第八章 根据 Table 生成 Model
Powered by GitBook
On this page
  • scope 传入参数
  • socope 的组合

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

可不可以有一种方式提前定义好 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 在模型关系定义里面以及说得非常清楚了,这里就不再进行赘述。

Previous第四章 模型查询Next第六章 生命周期函数 Hook

Last updated 7 years ago