Node - associate tables with Sequelize

别来无恙 提交于 2021-02-15 07:28:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!