【问题标题】:How to generate query on join table using Sequelize?如何使用 Sequelize 在连接表上生成查询?
【发布时间】:2020-04-27 02:31:49
【问题描述】:

假设有两个表,即用户和用户角色。 用户和用户角色之间的关系是一对多的。 用户的 Sequelize 模型如下 -

const user = sequelize.define(
  'user', {
    id: {
      type: DataTypes.BIGINT,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
      field: 'id'
    },
    userName: {
      type: DataTypes.STRING(200),
      allowNull: false,
      field: 'username'
    },
    password: {
      type: DataTypes.STRING(200),
      allowNull: false,
      field: 'password'
    }
  }, {
    tableName: 'user'
  }
);

用户角色的续集模型如下 -

const userRole = sequelize.define(
  'userRole', {
    id: {
      type: DataTypes.BIGINT,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
      field: 'id'
    },
    userId: {
      type: DataTypes.BIGINT,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
      field: 'user_id'
    },
    password: {
      type: DataTypes.STRING(200),
      allowNull: false,
      field: 'password'
    }
  }, {
    tableName: 'userRole'
  }
);

Sequelize 关联定义如下-

user.hasMany(models.userRole, { foreignKey: 'user_id', as: 'roles' });
userRole.belongsTo(models.user, { foreignKey: 'user_id', as: 'user' });

我想使用

生成以下查询
Sequelize -
SELECT * 
FROM   USER 
       INNER JOIN (SELECT user_role.user_id, 
                          role 
                   FROM   user_role 
                          INNER JOIN USER tu 
                                  ON tu.id = user_role.user_id 
                   GROUP  BY user_id 
                   ORDER  BY role) AS roles 
               ON USER.id = roles.user_id; 

我正在开发一个 API,前端网格将使用它来显示用户信息。用户角色表的角色属性具有搜索功能。如果匹配特定用户的任何角色,那么我希望用户记录包含与该用户关联的所有角色。

【问题讨论】:

    标签: sql node.js sequelize.js


    【解决方案1】:

    您必须使用包含(关于文档:https://sequelize.org/master/manual/models-usage.html#-code-findandcountall--code----search-for-multiple-elements-in-the-database--returns-both-data-and-total-count

    示例:

    
     Models.User.findAll({
        where :{
          id: userId
        },
        group: ['roles.user_id'],
        order: [['roles.role', 'ASC']] //or DESC, as you want
        include: {
          model: Models.UserRole,
          as: 'roles',
          attributes: ['user_id', 'role'],
          required: true
        },
      })
    
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      要获取与用户关联的所有角色,即使其中一个与查询匹配,您需要定义另一个关联,以便您可以在 sequelize 语句中包含角色表两次。

      User.hasMany(models.UserRole, { foreignKey: 'user_id', as: 'roles2' });
      

      Sequelize 语句 -

      const userInfo = await User.findAndCountAll({
        include: [
          {
            model: UserRole,
            attributes: ['id', 'role'],
            as: 'roles',
            where: { [Op.or]: [{ role: { [Op.like]: '%MANAGER%' } },
            required: true
          },
          {
            model: UserRole,
            attributes: ['id', 'role'],
            as: 'roles2',
            required: true
          } 
        ],
        where: whereStatement,
      });
      

      在第一个include(join)的帮助下,你可以根据用户角色过滤用户记录,在第二个include(join)的帮助下,你可以获得一个角色匹配的用户的所有角色.

      【讨论】:

        猜你喜欢
        • 2018-04-20
        • 2019-01-27
        • 2013-12-25
        • 2023-04-01
        • 2021-04-11
        • 2015-10-12
        • 1970-01-01
        • 2022-11-11
        • 1970-01-01
        相关资源
        最近更新 更多