【问题标题】:Sequelize: how to use `scope` inside `include`?Sequelize:如何在`include`中使用`scope`?
【发布时间】:2019-03-19 11:00:25
【问题描述】:

我想问是否可以在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 属于 Useruid

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

【问题讨论】:

    标签: javascript mysql sequelize.js


    【解决方案1】:

    尝试将您的范围附加到实际模型......它对我有用。

    Code.findOne({
      include: [{
        model: User.unscoped() 
      }],
    })
    

    @eee 更新 - 更清楚:

    Code.findOne({
      include: [{
        model: User.scope('activated', {method: ['inProvinces', provinces]}) 
      }],
    })
    

    我认为这应该可行...

    【讨论】:

    • 我不太明白。能详细点吗?
    猜你喜欢
    • 2020-12-13
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    相关资源
    最近更新 更多