How to implement many to many association in sequelize

前端 未结 4 668
庸人自扰
庸人自扰 2020-11-27 09:33

I have two tables: Books and Articles with a many-to-many relationship between them. Joining table is BookArticles.

models/books.js

module.exports =          


        
4条回答
  •  执念已碎
    2020-11-27 10:07

    This is how i solved the similar problem i had two models a user model

    var user = sequelize.define('user', {
        name: {
            Sequelize.STRING(255)
        },
        email: {
            type: Sequelize.STRING(255),
            unique: true,
            validate: {
                isEmail: true
            }
        }
    });
    

    and a roles model

    var Role = sequelize.define('role', {
        name: {
            Sequelize.ENUM('ER', 'ALL', 'DL')
        },
        description: {
            type: Sequelize.TEXT
        }
    });
    

    Then i created the union model UserRole

    var UserRole = sequelize.define('user_role', {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        name: {
            type: Sequelize.ENUM('Admin', 'Staff', 'Customer', 'Owner')
        }
    });
    

    Note: you have to explicitly define the id for UserRole otherwise sequelize will use the two foreign keys in this case user_id and role_id as your primary keys.

    Then i created the belongs to many relationship as follows

    User.belongsToMany(Role, { as: 'Roles', through: { model: UserRole, unique: false }, foreignKey: 'user_id' });
    Role.belongsToMany(User, { as: 'Users', through: { model: UserRole, unique: false }, foreignKey: 'role_id' });
    

提交回复
热议问题