范围(scope
): 定义好范围在后续的操作中可以减少条件的重复,如只选择未删除用户。
跟模型相关的地方都可以添加
// 修改默认所有操作的范围 default Scope
var Project = sequelize.define( 'project', {
// Attributes
}, {
defaultScope: {
where: {
active: true
}
},
scopes: {
deleted: {
where: {
deleted: true
}
},
activeUsers: {
include: [
{ model: User, where: { active: true } }
]
}
}
} );
// 移除默认范围,设置为 deleted 范围
Project.scope( 'deleted' ).findAll();
// 与上面等价
var DeletedProjects = Project.scope( 'deleted' );
DeletedProjects.findAll();
var 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' } );