简体   繁体   English

Sequelize —如何获得关联的模型?

[英]Sequelize — how to get associated model?

I have two associated models (abbreviated for clarity) 我有两个关联的模型(为简明起见,简称)

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
}

and

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

I create a new meeting, given an previously created user with id = 1 , as follows: 鉴于先前创建的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
}

How do I get sequelize to return the associated record without manually having to go through the associations and findOne them by id ? 我如何获得序列号以返回关联记录,而无需手动进行关联并通过id findOne它们?

Okay figured it out: 好了,想通了:

The solution is to do a reload after creation. 解决方案是在创建后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!
  })
}

I guess sequelize doesn't automatically reload after creation in case you never actually care about the model you just created, and you just want to know it got saved. 我猜想sequelize在创建后不会自动重新加载,以防您根本不关心刚刚创建的模型,而您只是想知道它已保存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM