问题
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
回答1:
I see one mistake in your code. You should use the same foreign key name for one to many relationships. Otherwise you will have two different columns in your database.
Here you should use userId as foreign key. Sequelize creates the id column in "belongsTo" model. So there will be a userId in Group model if you use it like this:
User.hasMany(models.Group, {foreignKey: 'userId', as: 'Group'});
Group.belongsTo(models.User, {foreignKey: 'userId', as: 'User'});
Also try not creating the associations in model files. Consider using index.js files and you can create all of your associations in there.
src
app.js
models
index.js
user.js
group.js
document.js
Keep you model definition in their files. Export the created model classes. Include them in your index.js file. Create necessary associations and export them again.
src/models/index.js
const User = require('./user');
const Group = require('./group');
const Document = require('./document');
User.hasMany(models.Group, {foreignKey: 'userId', as: 'Group'});
Group.belongsTo(models.User, {foreignKey: 'userId', as: 'User'});
// Define what associations you need.
module.exports = {
User,
Group,
Document
};
来源:https://stackoverflow.com/questions/62363328/node-associate-tables-with-sequelize