I want to ask if it's possible to use the scope of the associate model inside include
option?
In my case, there are two models, User
and 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
belongs to User
through uid
Code.belongsTo(User, {
foreignKey: 'uid',
targetKey: 'uid',
as: 'user',
})
I want to select a random Code
of users who are activated and in particular provinces. Is there any way to reuse activated
and inProvinces
scope so it may look like:
const randomCode = (provinces) =>
Code.findOne({
include: [{
model: User,
as: 'user',
scopes: ['activated', {method: ['inProvinces', provinces]}],
attributes: [],
required: true,
}],
order: sequelize.random(),
})
Try attaching your scope to the actual model.... it worked for me.
Code.findOne({
include: [{
model: User.unscoped()
}],
})
@eee Update - to be more clear:
Code.findOne({
include: [{
model: User.scope('activated', {method: ['inProvinces', provinces]})
}],
})
i think this should work...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With