Scopes作用域

Scoping allows you to define commonly used queries that you can easily use later. Scopes can include all the same attributes as regular finders, whereincludelimit etc.

Scoping允许你去定义普遍使用的查询,这样你之后就能够简单使用。Scopes能够像一般的查询器一样包含 whereincludelimit

Definition

Scopes are defined in the model definition and can be finder objects, or functions returning finder objects - except for the default scope, which can only be an object:

Scopes可以在模型定义中进行定义,也可以是查找器对象或返回查找器对象的函数-除了默认的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: {
[Op.gte]: value
}
}
}
}
}
});

You can also add scopes after a model has been defined by calling addScope. This is especially useful for scopes with includes, where the model in the include might not be defined at the time the other model is being defined.

你可以通过调用addScope在模型定义后添加scopes。这对带有includes的scopes十分有用,因为在其他模型被定义时include中的模型可能还没有定义

The default scope is always applied. This means, that with the model definition above, Project.findAll() will create the following query:

缺省scope总是被提供。这意味着有着上面的模型定义,Project.findAll()将创建出下面的查询:

SELECT * FROM projects WHERE active = true

The default scope can be removed by calling .unscoped().scope(null), or by invoking another scope:

缺省scope可以通过调用 .unscoped().scope(null)函数或调用另一个scope来移除

Project.scope('deleted').findAll(); // Removes the default scope

SELECT * FROM projects WHERE deleted = true

It is also possible to include scoped models in a scope definition. This allows you to avoid duplicating includeattributes or where definitions. Using the above example, and invoking the active scope on the included User model (rather than specifying the condition directly in that include object):

在scope定义中包含scoped模型也是可能的。这要求你避免重复 includeattributeswhere定义。使用上面的例子并在包含的User模型中调用active scope(而不是直接在包含对象中指明条件)

activeUsers: {
include: [
{ model: User.scope('active')}
]
}

Usage

Scopes are applied by calling .scope on the model definition, passing the name of one or more scopes. .scope returns a fully functional model instance with all the regular methods: .findAll.update.count.destroy etc. You can save this model instance and reuse it later:

Scopes通过在模型定义中调用.scope来应用,传递一个或多个scopes的名字。.scope将返回一个带着传统方法 .findAll.update.count.destroy
等的完整的函数模型实例。你可以保存这个模型实例并在之后重新使用它

const DeletedProjects = Project.scope('deleted');

DeletedProjects.findAll();
// some time passes // let's look for deleted projects again!
DeletedProjects.findAll();

Scopes apply to .find.findAll.count.update.increment and .destroy.

Scopes供应 .find.findAll.count.update.increment.destroy方法

Scopes which are functions can be invoked in two ways. If the scope does not take any arguments it can be invoked as normally. If the scope takes arguments, pass an object:

Scopes函数可以以两种方式被调用。如果scope不带任何参数,他将普通地调用。如果带参数,将传递对象:

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

SELECT * FROM projects WHERE someNumber =  AND accessLevel >= 

Merging

Several scopes can be applied simultaneously by passing an array of scopes to .scope, or by passing the scopes as consecutive arguments.

几个scopes可以同时通过传递scopes数组给 .scope来被应用,或者通过传递scopes作为连续的参数

// These two are equivalent
Project.scope('deleted', 'activeUsers').findAll();
Project.scope(['deleted', 'activeUsers']).findAll(); SELECT * FROM projects
INNER JOIN users ON projects.userId = users.id
AND users.active = true

If you want to apply another scope alongside the default scope, pass the key defaultScope to .scope:

如果你想要跟着缺省scope来应用其他scope,传递键defaultScope.scope

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

SELECT * FROM projects WHERE active = true AND deleted = true

When invoking several scopes, keys from subsequent scopes will overwrite previous ones (similar to _.assign). Consider two scopes:

当调用几个scopes时,来自子序列scopes的键将复写以前的键值

{
scope1: {
where: {
firstName: 'bob',
age: {
[Op.gt]:
}
},
limit:
},
scope2: {
where: {
age: {
[Op.gt]:
}
},
limit:
}
}

Calling .scope('scope1', 'scope2') will yield the following query

调用 .scope('scope1', 'scope2') 产生下面的查询:

WHERE firstName = 'bob' AND age >  LIMIT 

Note how limit and age are overwritten by scope2, while firstName is preserved. limitoffsetorderparanoidlock and raw are overwritten, while where and include are shallowly merged. This means that identical keys in the where objects, and subsequent includes of the same model will both overwrite each other.

注明怎么通过scope2复写limitage,当firstName保存时。whereinclude被浅合并时limitoffsetorderparanoidlock and raw
都被复写。这意味着在where对象中有着相同的键,并且当自序列包含相同的模型时将互相复写

The same merge logic applies when passing a find object directly to findAll on a scoped model:

当在scoped模型中直接传递一个find对象给findAll时,同样的合并逻辑使用

Project.scope('deleted').findAll({
where: {
firstName: 'john'
}
}) WHERE deleted = true AND firstName = 'john'

Here the deleted scope is merged with the finder. If we were to pass where: { firstName: 'john', deleted: false } to the finder, the deleted scope would be overwritten.

这里deleted scope将与查找器合并。如果我们打算传递where: { firstName: 'john', deleted: false }给查找器,deleted scope将被复写

Associations

Sequelize has two different but related scope concepts in relation to associations. The difference is subtle but important:

Sequelize有着两种不同但相关的与关联相关的scope概念。两者的不同很微弱,但却很重要

  • Association scopes Allow you to specify default attributes when getting and setting associations - useful when implementing polymorphic associations. This scope is only invoked on the association between the two models, when using the getsetadd and create associated model functions当getting和setting关联时,允许你指定属性-当实现多元化关联时十分有用。这个scope只有在两个模型的关联中被调用,使用getsetaddcreate关联模型函数
  • Scopes on associated models Allows you to apply default and other scopes when fetching associations, and allows you to pass a scoped model when creating associations. These scopes both apply to regular finds on the model and to find through the association.允许你在获取关联时请求默认或其他scopes,也允许你在创建关联时传递scoped模型。这个scopes即在模型中请求传统查询也通过关联进行查找

As an example, consider the models Post and Comment. Comment is associated to several other models (Image, Video etc.) and the association between Comment and other models is polymorphic, which means that Comment stores a commentable column, in addition to the foreign key commentable_id.

举例,考虑模型Post和Comment。Comment与几个模型关联(Image, Video等)且在Comment和其他模型之间的关联是多元化的,这意味着Comment存储commentable列,除此之外commentable_id为外键

The polymorphic association can be implemented with an association scope :

多元化关联可以使用关联scope实现:

this.Post.hasMany(this.Comment, {
foreignKey: 'commentable_id',
scope: {
commentable: 'post'
}
});

When calling post.getComments(), this will automatically add WHERE commentable = 'post'. Similarly, when adding new comments to a post, commentable will automagically be set to 'post'. The association scope is meant to live in the background without the programmer having to worry about it - it cannot be disabled. For a more complete polymorphic example, see Association scopes

当调用post.getComments()时,他将自动添加 WHERE commentable = 'post'。同样的,当添加新comment到post中时,commentable将会自动设置为 'post'。关联scope意味着存活在没有项目烦恼的后台-它不可能不可用。更多完成的多元化实例,看 Association scopes。

Consider then, that Post has a default scope which only shows active posts: where: { active: true }. This scope lives on the associated model (Post), and not on the association like the commentable scope did. Just like the default scope is applied when calling Post.findAll(), it is also applied when calling User.getPosts() - this will only return the active posts for that user.

考虑这些后,Post有了只显示活跃posts:where: { active: true }的缺省scope。这个scope存活在关联的模型(Post)中,而不在像commentable scope做出的关联中。当调用Post.findAll()和User.getPosts()时,缺省scope被请求-将只返回活跃posts

To disable the default scope, pass scope: null to the getter: User.getPosts({ scope: null }). Similarly, if you want to apply other scopes, pass an array like you would to .scope:

为了使缺省scope无效,传递scope: null给getter: User.getPosts({ scope: null })。相同的,如果你想要请求其他scopes,只要传递数组,就像你传递给.scope的那样:

User.getPosts({ scope: ['scope1', 'scope2']});

If you want to create a shortcut method to a scope on an associated model, you can pass the scoped model to the association. Consider a shortcut to get all deleted posts for a user:

如果你想要创建快捷方法去一个关联模型的scope,你可以传递scoped模型给关联。考虑快捷方式将得到所有删除的posts给用户

const Post = sequelize.define('post', attributes, {
defaultScope: {
where: {
active: true
}
},
scopes: {
deleted: {
where: {
deleted: true
}
}
}
}); User.hasMany(Post); // regular getPosts association
User.hasMany(Post.scope('deleted'), { as: 'deletedPosts' }); User.getPosts(); // WHERE active = true
User.getDeletedPosts(); // WHERE deleted = true

Sequelize-nodejs-9-Scopes的更多相关文章

  1. 【前端】nodejs的ORM框架sequelize的工厂化

    转载请注明出处:http://www.cnblogs.com/shamoyuu/p/sequelize_factory.html 一.什么是sequelize nodejs的后台在操作数据库的时候,需 ...

  2. Node.js Koa2开发微信小程序服务端

    1.promise.async.await const Koa = require('koa') const app = new Koa() // 应用程序对象 有很多中间件 // 发送HTTP KO ...

  3. nodejs项目mysql使用sequelize支持存储emoji

    nodejs项目mysql使用sequelize支持存储emoji 本篇主要记录nodejs项目阿里云mysql如何支持存储emoji表情. 因由 最近项目遇到用户在文本输入emoji进行存储的时候导 ...

  4. koa2+log4js+sequelize搭建的nodejs服务

    主要参考http://www.jianshu.com/p/6b816c609669这篇文章 npm安装使用国内taobao镜像,速度更快些 npm --registry https://registr ...

  5. 从 moment -> nodejs -> sequelize -> postgres,你都得设置好时区

    背景 最近在做报表统计,因为 sequelize 的时区配置没加导致了统计数字对不上的问题. 问:大家都知道时区,但是你清楚 UTC 和 GMT 的区别吗? 答:UTC 是我们现在用的时间标准,GMT ...

  6. nodejs sequelize 对应数据库操作符的定义

    const Op = Sequelize.Op [Op.and]: {a: } // 且 (a = 5) [Op.or]: [{a: }, {a: }] // (a = 5 或 a = 6) [Op. ...

  7. postgresql on centos (sequelize+pg+nodejs):Failed to find PostgresSQL server.Pleast double check your settings

    公司的一个项目,使用的nodejs做服务端,数据库是postgresql,在本地时一切ok,放在centos时,postgresql配置ok,可以远程访问,但是nodejs在centos启动时,就会报 ...

  8. 项目总结,彻底掌握NodeJS中如何使用Sequelize

    前言 sequelize是什么? sequelize是基于NodeJs的ORM框架,它适用于不同的数据库,如:Postgres.MySQL.SQLite.MariaDB,我们可以通过sequelize ...

  9. 基于Nodejs的sequelize操纵数据库

    ## 使用基于ORM架构的sequelize操纵数据库 ### 1.技术背景 ```Sequelize是一个基于promise的关系型数据库ORM框架,*********************技术文 ...

  10. Nodejs ORM框架Sequelize快速入门

    Nodejs ORM框架Sequelize快速入门 什么是ORM? 简单的讲就是对SQL查询语句的封装,让我们可以用OOP的方式操作数据库,优雅的生成安全.可维护的SQL代码.直观上,是一种Model ...

随机推荐

  1. @ConfigurationProperties与@value区别

    @ConfigurationProperties与@value区别   @ConfigurationProperties @value 功能 批量注入配置文件中的属性 一个个指定 松散绑定 支持 不支 ...

  2. AutoFac使用方法总结四:生命周期续

         控制反转(IoC/Inverse Of Control):   调用者不再创建被调用者的实例,由autofac框架实现(容器创建)所以称为控制反转.      依赖注入(DI/Depende ...

  3. 在pom.xml中添加Spring依赖

    <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://mave ...

  4. .NET Core 微服务架构-Docker部署

    本文主要介绍通过Docker来部署通过.NET Core开发的微服务架构,部署的微服务主要包括统一网关(使用Ocelot开发).统一认证(IdentityServer4).应用服务(ASP.NET C ...

  5. ENVI对一种WGS84投影不支持的情况说明

    作者:朱金灿 来源:http://blog.csdn.net/clever101 假如wkt字符串这样描述WGS84投影: GEOGCS["GCS_WGS_1984",DATUM[ ...

  6. C#防止WebBrowser在新窗口中打开链接页面

    在日常的开发中,大家有时需要用WebBrowser加载URL,来实现某些功能.而这时,我们就不希望所打开的页面中的链接,在新窗口中打开,因为这样的话,实际上是用系统默认的浏览器打开了,从而脱离了你的W ...

  7. Android Apk增量更新

    前言 有关APK更新的技术比较多,例如:增量更新.插件式开发.热修复.RN.静默安装. 下面简单介绍一下: 什么是增量更新?   增量更新就是原有app的基础上只更新发生变化的地方,其余保持原样. 与 ...

  8. Pig autocomplete 自动补全

    在pig的grunt环境下,按TAB键可以自动补全命令,用户可以添加自己的补全信息. 在conf目录下创建autocomplete文件,添加如下内容: hdfs://vm1:8020/   在grun ...

  9. shell_script2

    一.函数 1.简介 Shell函数类似于Shell脚本,里面存放了一系列的指令 不过,Shell的函数存在于内存,而不是硬盘文件,所以速度很快 另外,Shell还能对函数进行预处理,所以函数的启动比脚 ...

  10. 网站换了HTTPS后残留部分http处理方式

    网站换了HTTPS后残留部分http处理方式,以前添加的文章里面是有http的,导致浏览器打开网站的时候提示证书不安全,解决方法很简单 在html页面上加上这一段话 <!-- 强制让http的访 ...