Gustavo Bordin
Gustavo Bordin

Reputation: 109

Node - associate tables with Sequelize

I'm trying to associate tables in such a way that:

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

Upvotes: 1

Views: 3251

Answers (1)

Mansur Ali Koroglu
Mansur Ali Koroglu

Reputation: 1918

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 a foreign key. Sequelize creates the id column in the belongsTo model. So there will be a userId in the Group model if you use it like this:

User.hasMany(Group, {foreignKey: 'userId', as: 'Group'});
Group.belongsTo(User, {foreignKey: 'userId', as: 'User'});

Also, try not to create 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 your 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(Group, {foreignKey: 'userId', as: 'Group'});
Group.belongsTo(User, {foreignKey: 'userId', as: 'User'});

// Define what associations you need.

module.exports = {
    User,
    Group,
    Document
};

Upvotes: 7

Related Questions