簡體   English   中英

Sequelize v3 - 如何將hasMany關系的默認值設為空列表?

[英]Sequelize v3 — how do I make the default value for a hasMany relationship an empty list?

我使用Sequelize作為我的ORM。 我有一個簡單的User模型如下。 一個User hasMany commentsComment 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

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

測試通過就好了。

我怎么能告訴Sequelize只是將一個空的評論列表作為默認值?

實際上,此功能不是模型創建的一部分。

它與獲取數據時的查詢有關。 您可以在findAll的include語句中使用nested:true選項。

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

來源: http//docs.sequelizejs.com/manual/models-usage.html#nested-eager-loading

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM