[英]Sequelize: how to use `scope` inside `include`?
我想问一下是否可以在include
选项中使用关联模型的范围?
就我而言,有两个模型, User
和Code
:
const ACTIVE_FIELDS = ['fullname', 'idCard']
const User = sequelize.define('User', {
uid: DataTypes.STRING,
fullname: DataTypes.TEXT,
idCard: DataTypes.STRING,
province: DataTypes.STRING,
}, {
scopes: {
activated: {
where: ACTIVE_FIELDS.reduce((condition, field) => {
condition[field] = {[sequelize.Op.ne]: null}
return condition
}, {}),
},
inProvinces: (provinces) => ({
where: {
province: {
[sequelize.Op.in]: provinces,
},
},
}),
},
})
const Code = sequelize.define('Code', {
id: {
type: DataTypes.STRING,
primaryKey: true,
},
uid: DataTypes.STRING,
}, {});
Code
通过uid
属于User
Code.belongsTo(User, {
foreignKey: 'uid',
targetKey: 'uid',
as: 'user',
})
我想选择一个随机激活的用户Code
,尤其是特定省份。 有没有办法重用activated
和inProvinces
范围,所以它可能看起来像:
const randomCode = (provinces) =>
Code.findOne({
include: [{
model: User,
as: 'user',
scopes: ['activated', {method: ['inProvinces', provinces]}],
attributes: [],
required: true,
}],
order: sequelize.random(),
})
尝试将您的范围附加到实际模型......它对我有用。
Code.findOne({
include: [{
model: User.unscoped()
}],
})
@eee 更新 - 更清楚:
Code.findOne({
include: [{
model: User.scope('activated', {method: ['inProvinces', provinces]})
}],
})
我认为这应该有效...
我实现了一个简单的辅助函数来提取范围的where
属性:
const scope = (model, scopeName, ...params) => {
let scope = model.options.scopes[scopeName]
if (!scope) { return }
if (typeof scope === 'function') { scope = scope(...params) }
return scope.where
}
在查询中,我可以使用:
Code.findOne({
include: [{
model: User,
as: 'user',
where: {
...scope(User, 'activated'),
...scope(User, 'inProvinces', provinces),
},
}],
})
这种方法存在很多问题,因为它忽略了where
以外的所有其他属性。 希望有人可以提出更好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.