Home Reference Source Repository Join us on Slack
Sandals Shoes Cushioned Beige Strappy Slingback Wide Ladies Lolittas Size 6 Block High T Embellished Summer Gladiator Toe Thick Fit Peep Heel Roman 2 CqWft Sandals Shoes Cushioned Beige Strappy Slingback Wide Ladies Lolittas Size 6 Block High T Embellished Summer Gladiator Toe Thick Fit Peep Heel Roman 2 CqWft Sandals Shoes Cushioned Beige Strappy Slingback Wide Ladies Lolittas Size 6 Block High T Embellished Summer Gladiator Toe Thick Fit Peep Heel Roman 2 CqWft Sandals Shoes Cushioned Beige Strappy Slingback Wide Ladies Lolittas Size 6 Block High T Embellished Summer Gladiator Toe Thick Fit Peep Heel Roman 2 CqWft Sandals Shoes Cushioned Beige Strappy Slingback Wide Ladies Lolittas Size 6 Block High T Embellished Summer Gladiator Toe Thick Fit Peep Heel Roman 2 CqWft Sandals Shoes Cushioned Beige Strappy Slingback Wide Ladies Lolittas Size 6 Block High T Embellished Summer Gladiator Toe Thick Fit Peep Heel Roman 2 CqWft
Manual » Tutorial

Sandals Shoes Cushioned Beige Strappy Slingback Wide Ladies Lolittas Size 6 Block High T Embellished Summer Gladiator Toe Thick Fit Peep Heel Roman 2 CqWft

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

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:

const Project = sequelize.define('project', { // Attributes }, { defaultScope: { where: { active: true } }, scopes: Fit Embellished Block Beige Strappy Slingback Sandals Peep T Size High Thick Toe Ladies Heel Shoes Summer Lolittas 6 Cushioned 2 Gladiator Wide Roman { deleted: { where: { deleted: true } }, activeUsers: { include: [ { model: User, where2 Peep Toe Slingback Lolittas Wide 6 Beige Block Cushioned Ladies Heel Size Thick Gladiator Sandals Embellished Roman T Summer Shoes Strappy High Fit : { active: true }} ] }, random: function () { return { where: { someNumber: Math.random() } } }, accessLevel: function (value) { return { where: { accessLevel: Sandals 2 Size Wide Shoes T Ladies Strappy Heel Thick Cushioned Slingback High Summer Beige Gladiator Lolittas Peep Roman 6 Embellished Toe Block Fit { [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.

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

SELECT *Beige Fit Lolittas Strappy Summer Embellished Sandals Peep Slingback Roman Size Heel T Shoes Ladies Thick 6 Block High Wide Toe Cushioned 2 Gladiator FROM projects WHERE active= Sandals Lolittas Embellished Peep Cushioned Fit Strappy High 2 Wide Size Gladiator Beige Summer Thick Slingback Shoes Roman 6 T Toe Heel Ladies Block true

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

ProjectStrappy 2 Heel Thick T Embellished Fit Beige 6 Lolittas Block Peep Toe High Ladies Wide Sandals Roman Shoes Size Summer Gladiator Slingback Cushioned .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 include, attributes 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):

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:

const DeletedProjects = ProjectMartens Boot Virginia Unisex Adults' Brogues Dr Hazil Virginia Leather Black Black f6qdpI.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 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:

Project.scope('random',Heel 6 Toe Fit Cushioned Strappy 2 Thick Roman Slingback Lolittas Embellished Sandals Summer Size Ladies Beige T High Shoes Wide Peep Gladiator Block { method: ['accessLevel', 19]}).findAll();
SELECT * FROM projects WHERE someNumber = 42 AND accessLevel >= 19

Merging

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

// These two are equivalent Project.scope('deleted', 'activeUsers'Roman Embellished 6 Block Heel Size Gladiator Cushioned T Lolittas Shoes Toe Beige Ladies Fit Sandals Peep Strappy 2 Thick Wide High Slingback Summer ).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:

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:

{ scope1: { where: { firstName: 'bob', age: { [Op.gt]: 20 } }, limit: 2 }, scope2: { where: { age: { [Op.gt]: 30 } }, limit: 10 }Strappy Size Fit Heel T High Block Peep Toe Shoes 6 Lolittas Summer Slingback Gladiator Sandals Roman Embellished Cushioned 2 Beige Thick Wide Ladies }

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

WHERE firstName = 'bob' AND age > 30 LIMIT 10

Note how limit and age are overwritten by scope2, while firstName is preserved. limit, offset, order, paranoid, lock 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.

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

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.

Associations

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

  • 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 get, set, add and create associated model functions
  • 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.

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.

The polymorphic association can be implemented with an association 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

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.

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:

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:

const Post = sequelize.define('post', attributes, { defaultScope: { where: { active: true } }, scopes: { deleted: { where: { deleted: true } } } }); Block Embellished Gladiator Wide Slingback Strappy Sandals Ladies Lolittas Summer High Fit Roman Cushioned T 2 Heel Peep Size 6 Beige Thick Toe Shoes User.hasMany(Post); // regular getPosts association User.hasMany(Post.scope('deleted'), { as: 'deletedPosts' });
User.getPosts(); // WHERE active = true User.getDeletedPosts(); // WHERE deleted = true