I'm trying to associate tables in such a way that:
- A group has many documents
- A document belongs to a group
- A group belongs to an user
- An user has many groups
When i try to list all from table 'Group' including 'User', throws an error saying that User is not associated to Group.
My models:
Document.js
const Document = conn.define('document', {
title: {
type: Sequelize.TEXT,
allowNull: false
},
content: {
type: Sequelize.TEXT,
allowNull: false
},
footer: {
type: Sequelize.TEXT,
}
})
Document.sync()
Document.associate = (models) => {
Document.belongsTo(models.Group, {foreignKey: 'groupId', as: 'Group'})
}
module.exports = Document
Group.js
const Group = conn.define('group', {
name: {
type: Sequelize.STRING,
allowNull: false
},
})
Group.sync()
Group.associate = (models) => {
Group.hasMany(models.Document, {foreignKey: 'groupId', as: 'Document'})
Group.belongsTo(models.User, {foreignKey: 'userId', as: 'User'})
}
module.exports = Group
User.js
const User = conn.define('user', {
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
},
password: {
type: Sequelize.STRING
},
})
User.sync()
User.associate = (models) => {
User.hasMany(models.Group, {foreignKey: 'groupId', as: 'Group'})
}
module.exports = User
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…