简体   繁体   English

是sequelize上的belongsToMany自动创建新的联接表?

[英]is belongsToMany on sequelize automatically create new join table?

I'm new in this sequelize things. 我是新手。 I try to associate model between Users and Permissions through UserPermissions using belongsToMany, and this is my code. 我尝试使用belongsToMany通过UserPermissions在Users和Permissions之间关联模型,这是我的代码。

-- users.js -users.js

const bcrypt = require('bcrypt');
const config = require('../config/general');

module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', {
        email: {
            type: DataTypes.STRING,
            allowNull: false,
            unique: true,
            validate: {
                isLowercase: true,
                notEmpty: true,
                isEmail: true
            }
        },
        username: {
            type: DataTypes.STRING,
            allowNull: false,
            unique: true,
            validate: {
                isLowercase: true,
                notEmpty: true,
                min: 3
            }
        },
        salt: {
            type: DataTypes.STRING,
            allowNull: true
        },
        password: {
            type: DataTypes.STRING,
            allowNull: false,
            validate: {
                notEmpty: true
            }
        },
    }, {
        underscored: true,
        classMethods: {
            associate: (models) => {
                User.belongsToMany(models.Permission, {
                    through: 'UserPermissions', 
                    foreignKey: 'user_id'
                });
            },
            validPassword: (password, passwd, done) => {
                const tmppass = password + config.secret;
                bcrypt.compare(tmppass, passwd, (err, isMatch) => {
                    if (err) return done(err);
                    return done(null, isMatch);
                });
            }
        }
    });

    User.beforeCreate( (user, option, done) => {
        bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
            if (err) return done(err);
            const tmppass = user.password + config.secret;
            bcrypt.hash(tmppass, salt, (err, hash) => {
                if (err) return done(err);
                user.salt       = salt;
                user.password   = hash;
                return done(null, user);
            });
        });
    });

    return User;
};

-- permissions.js --Permissions.js

module.exports = (sequelize, DataTypes) => {
    const Permission = sequelize.define('Permission', {
        name: {
            type: DataTypes.STRING,
            allowNull: false,
            validate: {
                notEmpty: true
            }
        },
        slug: {
            type: DataTypes.STRING,
            validate: {
                isLowercase: true
            }
        },
        description: {
            type: DataTypes.TEXT
        }
    }, {
        underscored: true,
        classMethods: {
            associate: (models) => {
                Permission.belongsToMany(models.User, { 
                    through: 'UserPermissions', 
                    foreignKey: 'permission_id'
                });
            }
        }
    });

    return Permission;
};

According to sequelize docs about belongsToMany in here , belongsToMany will create a new model that link to whatever model that you join, right. 据有关belongsToMany在sequelize文档这里 ,belongsToMany将创建一个新模型,链接到任何模型,你加入吧。

This will create a new model called UserProject with the equivalent foreign keys projectId and userId. 这将创建一个具有等效外键projectId和userId的名为UserProject的新模型。 Whether the attributes are camelcase or not depends on the two models joined by the table (in this case User and Project). 属性是否为驼峰格式取决于表连接的两个模型(在这种情况下为User和Project)。 Sequelize Belongs-To-Many 续集属于多个

But when I try that and migrate it using sequelize-cli , I didn't see any join table that had been created. 但是,当我尝试使用sequelize-cli迁移它时,我没有看到任何已创建的sequelize-cli表。 The Users Table is created, The Permissions Table is created, but UserPermissions Table is not created. 该表的用户创建,创建权限表,但不是会创建UserPermissions表。 Did I miss some thing in here? 我想念这里的东西吗? or there is something wrong with my code? 还是我的代码有问题?

I'm using postgres dialect, "pg": "^6.4.0" and "sequelize": "^4.3.1" 我使用的是postgres方言, "pg": "^6.4.0""sequelize": "^4.3.1"

Oh ya, I'm really sorry about my english, I'm not really good in english. 噢,我真的很抱歉我的英语,我的英语不是很好。

To answer your question (many years later): 要回答您的问题(很多年后):

You were likely told by the documentation to do this to create a join table: 文档可能告诉您执行此操作以创建联接表:

In your User associations: 在您的用户关联中:

User.belongsToMany(models.Permission, {
                    through: 'UserPermissions', 
                    foreignKey: 'user_id'
                });

In your Permission associations: 在您的权限关联中:

Permission.belongsToMany(models.User, { 
                    through: 'UserPermissions', 
                    foreignKey: 'permission_id'
                });

The portion of the process not mentioned in the documentation is how to actually create this table that you use in the database. 文档中未提及的过程部分是如何实际创建您在数据库中使用的表。 To create the table used by these functions in the database, create a migration with the following code: 要在数据库中创建这些功能使用的表,请使用以下代码创建迁移:

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('UserPermissions', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      permission_id: {
        type: Sequelize.INTEGER,
        references: {
          model: 'Permissions',
          key: 'id',
          as: 'permission_id'
        }
      },
      user_id: {
        type: Sequelize.INTEGER,
        references: {
          model: 'Users',
          key: 'id',
          as: 'user_id'
        }
      },
      createdAd: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    })
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('UserPermissions')
  }
}

Using the Sequelize CLI will generate most of this code for you. 使用Sequelize CLI将为您生成大部分代码。 Note that the model object property under references is the table name in postgres (well, this is what worked for me). 请注意, references下的model对象属性是postgres中的表名(嗯,这对我有用)。

EDIT: 编辑:

Also note that the through property should be a model, so: 另请注意, through属性应为模型,因此:

through: models.UserPermission

and create the relevant model. 并创建相关模型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM