Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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(),
  })
like image 543
eee Avatar asked Oct 15 '18 03:10

eee


Video Answer


1 Answers

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...

like image 169
Nawlbergs Avatar answered Oct 18 '22 02:10

Nawlbergs