gpt4 book ai didi

javascript - Sequelize : how to use `scope` inside `include` ?

转载 作者:行者123 更新时间:2023-11-29 02:40:41 26 4
gpt4 key购买 nike

我想问一下是否可以在 include 选项中使用关联模型的范围?

在我的例子中,有两个模型,UserCode:

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 激活用户和特定省份。有什么方法可以重用 activatedinProvinces 范围,所以它看起来像:

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]})
}],
})

我认为这应该可行...

关于javascript - Sequelize : how to use `scope` inside `include` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52809572/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com