首页 文章

isSentaMany属于sequelize会自动创建新的连接表吗?

提问于
浏览
3

我是这个续集事物的新手 . 我尝试使用belongsToMany通过UserPermissions关联用户和权限之间的模型,这是我的代码 .

-- 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

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;
};

根据here中关于belongsToMany的sequelize文档,belongsToMany将创建一个新模型,链接到您加入的任何模型,对 .

这将创建一个名为UserProject的新模型,其中包含等效的外键projectId和userId . 属性是否为camelcase取决于表连接的两个模型(在本例中为User和Project) . Sequelize Belongs-To-Many

但是当我尝试使用 sequelize-cli 进行迁移时,我没有看到任何已创建的连接表 . 创建了 Users 表,创建了 Permissions 表,但未创建 UserPermissions 表 . 我在这里想念一些东西吗?或者我的代码有问题?

我正在使用 postgres 方言, "pg": "^6.4.0""sequelize": "^4.3.1"

噢,我真的很抱歉我的英语,我的英语不是很好 .

1 回答

  • 0

    回答你的问题(许多年后):

    文档可能会告诉您这样做以创建连接表:

    在您的用户关联中:

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

    在您的权限关联中:

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

    文档中未提及的过程部分是如何实际创建您在数据库中使用的表 . 要在数据库中创建这些函数使用的表,请使用以下代码创建迁移:

    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')
      }
    }
    

    使用Sequelize CLI将为您生成大部分代码 . 请注意 references 下的 model 对象属性是postgres中的表名(嗯,这对我有用) .

    编辑:

    另请注意, through 属性应为模型,因此:

    through: models.UserPermission
    

    并创建相关模型 .

相关问题