我正在使用Sequelize作为我的 ORM。我有一个简单的 User
模型,如下所示。一个 User
hasMany
comments
和一个 Comment
belongsTo
一个 user
.
models/user.js
( trim 为相关内容)
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
(也已 trim )
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
我创建了一个测试,如下所示(为了简洁而进行了 trim )
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 将空评论列表设置为默认值?
最佳答案
实际上,此功能不是模型创建的一部分。
与获取数据时的Query相关。 您可以在findAll的include语句中使用nested:true选项。
User.findAll({
include: [{
model: Comment,
as: "comments",
nested: true
}]});
来源:http://docs.sequelizejs.com/manual/models-usage.html#nested-eager-loading
关于javascript - Sequelize v3 — 如何将 hasMany 关系的默认值设置为空列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40336935/