-
Notifications
You must be signed in to change notification settings - Fork 1
Scopes
Radosław Mejer edited this page May 9, 2020
·
1 revision
When some query constraints start to duplicate in your application you can define a scope function in the model. It will add a new method to query builder which will apply defined constraints.
const User = kex.createModel('User', {
scopes: {
active (qb) {
qb.where('active', true)
}
}
})
Scopes can accept arguments:
const User = kex.createModel('User', {
scopes: {
role (qb, roleName) {
qb.where('role', roleName)
}
}
})
const admins = await User.active()
.role('admin')
Scopes can be used in inner where()
queries:
const jonAdmins = await User.active()
.where(qb => {
qb.role('admin')
.where('name', 'Jon')
})
Unlike in Knex, scopes don't have a 'or* (
orRole) query methods. If you want to join them using "OR" statement you'll need to combine them with
orWhere` method:
const adminsOrUsers = await User.query()
.role('admin')
.orWhere(qb => qb.role('user'))
Global scopes are something similar to "local" scopes. The main differences are:
- they apply automatically to every query (including updates and deletes)
- they don't accept any arguments
const User = kex.createModel('User', {
globalScopes: {
active (qb) {
qb.where('active', true)
}
}
})
The model query builder allows ignoring selected global scopes. This can be done in a few ways:
-
withoutGlobalScope(name)
ignore single scope -
withoutGlobalScopes([name])
ignore list of scopes -
withoutGlobalScopes()
ignore all global scopes