Sequelize v3 - 如何将hasMany关系的默认值设为空列表?

问题描述 投票:1回答:1

我使用Sequelize作为我的ORM。我有一个简单的User模型如下。 Qazxswpoi User hasManycomments Comment a belongsTo

user(修剪到相关的)

models/user.js

const model = (sequelize, DataTypes) => { const User = sequelize.define('User', { name: { type: DataTypes.STRING } }, { classMethods: { associate: function(models) { User.hasMany(models.Comment, {as: 'comments'}) } } } ) return User } module.exports = model (也修剪)

models/comment.js

我创建了一个测试如下(为简洁而修剪)

const model = (sequelize, DataTypes) => {

  const Comment = sequelize.define('Comment', {
      text: {
        type: DataTypes.TEXT
      }
    }, {
      classMethods: {
        associate: function(models) {
          Comment.belongsTo(models.User, {as: 'author'})
        }
      }
    }
  )

  return Comment
}

module.exports = model

结果

describe('create user given simple valid data', () => {
  const userData = {
    name: 'test'
  }

  it('creates a user', (done) => {
    User.create(userData, {
      include: [{model: models.Comment, as: 'comments'}]
    }).then((user) => {
      const userJS = user.get({plain: true})
      expect(userJS).to.have.property('name')
      expect(userJS).to.have.property('comments')
      done()
    }, done)
  })
})

如果我这样指定我的Unhandled rejection AssertionError: expected { Object (name, ...) } to have a property 'comments'

userData

测试通过就好了。

我怎么能告诉Sequelize只是将一个空的评论列表作为默认值?

javascript associations sequelize.js model-associations
1个回答
0
投票

实际上,此功能不是模型创建的一部分。

它与获取数据时的查询有关。您可以在findAll的include语句中使用nested:true选项。

const userData = {
  name: 'test',
  comments: []
}

来源:User.findAll({ include: [{ model: Comment, as: "comments", nested: true }]});

© www.soinside.com 2019 - 2024. All rights reserved.