Sequelize - 如何获得相关模型?

时间:2016-11-16 00:21:26

标签: javascript node.js associations sequelize.js

我有两个相关模型(为清晰起见缩写)

const model = (sequelize, DataTypes) => {

  const User = sequelize.define('User', {
      fullName: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notEmpty: true,
          len: [1,255]
        }
      }
    },
    {
      classMethods: {
        associate: function(models) {
          User.hasMany(models.Meeting, {as: 'chairedMeetings', foreignKey: 'chairmanId'})
        }
      }
    }
  )

  return User
}

const model = (sequelize, DataTypes) => {

  const Meeting = sequelize.define('Meeting', {
      title: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notEmpty: true,
          len: [1,255]
        }
      }
    }, {
      classMethods: {
        associate: function(models) {
          Meeting.belongsTo(models.User, {as: 'chairman'})
        }
      }
    }
  )

  return Meeting
}

module.exports = model

我为之前创建的id = 1用户创建了一个新会议,如下所示:

const data = {
  title: 'Some amazing meeting title',
  chairmanId: 1
}

Meeting.create(data, {include: [{all: true, nested: true}]}).then(meeting => {
  const chairmanId = meeting.get('chairmanId') // ===> this is 1 as expected
  const chairman = meeting.get('chairman')     // ===> but this is undefined
}

如何获取sequelize以返回相关记录,而无需手动完成关联,并findOne id对其进行检查?

1 个答案:

答案 0 :(得分:1)

好的想通了:

解决方案是在创建后执行reload

Meeting.create(data, {include: [{all: true, nested: true}]}).then(meeting => {
  const chairmanId = meeting.get('chairmanId') // ===> this is 1 as expected
  meeting.reload({include: [{all: true, nested: true}]}).then(reloadedMeeting => {
    const chairman = reloadedMeeting.get('chairman') // ===> is a user!
  })
}

我想sequelize不会在创建后自动重新加载,以防你真正关心刚创建的模型,而你只是想知道它已经保存了。