簡體   English   中英

是sequelize上的belongsToMany自動創建新的聯接表?

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

我是新手。 我嘗試使用belongsToMany通過UserPermissions在Users和Permissions之間關聯模型,這是我的代碼。

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

據有關belongsToMany在sequelize文檔這里 ,belongsToMany將創建一個新模型,鏈接到任何模型,你加入吧。

這將創建一個具有等效外鍵projectId和userId的名為UserProject的新模型。 屬性是否為駝峰格式取決於表連接的兩個模型(在這種情況下為User和Project)。 續集屬於多個

但是,當我嘗試使用sequelize-cli遷移它時,我沒有看到任何已創建的sequelize-cli表。 該表的用戶創建,創建權限表,但不是會創建UserPermissions表。 我想念這里的東西嗎? 還是我的代碼有問題?

我使用的是postgres方言, "pg": "^6.4.0""sequelize": "^4.3.1"

噢,我真的很抱歉我的英語,我的英語不是很好。

要回答您的問題(很多年后):

文檔可能告訴您執行此操作以創建聯接表:

在您的用戶關聯中:

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

並創建相關模型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM