【问题标题】:Trying to search entity with association Many to Many Sequelize尝试搜索具有关联多对多续集的实体
【发布时间】:2020-05-29 10:47:10
【问题描述】:

问题简历: 当我尝试执行 findOne 或 findAll 时遇到问题。 在 findOne 或 findAll 答案中,我捕获了用户的所有信息,但在答案中没有与该用户关联的任何“t_roles”数据。 但奇怪的问题是,如果我在 findOne 中使用raw: true,就会显示角色信息。

我有两个模型

用户:

const dbUser = {
  a_id: {
    primaryKey: true,
    autoIncrement: true,
    type: Sequelize.BIGINT,
  },
  a_date_created: {
    type: Sequelize.DATE,
    allowNull: false,
  },
  a_first_name: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  a_last_name: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  a_email: {
    type: Sequelize.TEXT,
    unique: true,
    allowNull: false,
  },
  a_password: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  a_birthday: {
    type: Sequelize.DATE,
    allowNull: false,
  },
  a_is_active: {
    type: Sequelize.BOOLEAN,
    allowNull: false,
  },
};

User.init(dbUser, {
  sequelize: db,
  modelName: 't_user',
  timestamps: false,
  tableName: 't_users',
});


User.associate = (models) => {
  console.log('ASSOCIADO')
  User.belongsToMany(models.Role, {
    through: { model: UserRole, unique: false },
    as: 'roles',
    foreignKey: 'a_user',
    otherKey: 'a_role',
  });
};

和角色:

const dbRole = {
  a_id: {
    primaryKey: true,
    autoIncrement: true,
    type: Sequelize.BIGINT,
  },
  a_role: {
    type: Sequelize.STRING,
    allowNull: false,
  },
};

Role.init(dbRole, {
  sequelize: db,
  modelName: 't_role',
  timestamps: false,
  tableName: 't_roles',
});

Role.associate = (models) => {
  Role.belongsToMany(models.User, {
    through: { model: UserRole, unique: false },
    as: 'UserOfRoles',
    foreignKey: 'a_role',
    otherKey: 'a_user',
  });
};

如您所见,我正在使用另一个模型 UserRole 关联它们:

const dbUserRole = {
  a_id: {
    primaryKey: true,
    autoIncrement: true,
    type: Sequelize.BIGINT,
  },
  a_role: {
    type: Sequelize.INTEGER,
    allowNull: false,
    primaryKey: false,
    references: {
      model: Role,
      key: 'a_id',
    },
    onDelete: 'CASCADE',
  },
  a_user: {
    type: Sequelize.INTEGER,
    allowNull: false,
    references: {
      model: User,
      key: 'a_id',
    },
    onDelete: 'CASCADE',
  },
};

UserRole.init(dbUserRole, {
  sequelize: db,
  modelName: 't_user_role',
  timestamps: false,
  tableName: 't_user_role',
});


UserRole.associate = (models) => {
  UserRole.belongsTo(models.User, { targetKey: 'a_id', foreignKey: 'a_user' });
  UserRole.belongsTo(models.Role, { targetKey: 'a_id', foreignKey: 'a_role' });
};

要创建一个具有角色(管理员)的用户,我喜欢下面的代码:

onst createAdmin = async (body) => {
  try {
    const userResult = await createUser(body);
    if (userResult.error) {
      return {
        ok: false,
        error: userResult.error,
      };
    }
    const isAdmin = await UserRole.create({
      a_role: 1,
      a_user: userResult.a_user_id,
    });

    return {
      ok: true,
    };
  } catch (error) {
    return {
      ok: false,
      error,
    };
  } 

似乎工作正常,因为正在创建用户,并且也使用“t_user_role”进行关联,因为也在表中创建数据。 当我对问题简历感到难过时,我的麻烦是当我尝试执行 findOne 或 findAll 时。 例如,当我尝试下面的代码时,我捕获了用户的所有信息,但在答案中没有任何与该用户关联的“t_roles”数据。

const { body } = req;
  try {
    const result = await User.findOne({
      where: {
        a_id: 1,
      },
      include: [
        {
          association: 'roles',
          attributes: ['a_role'],
          through: {
            attributes: [],
          },
        },
      ],
    });
    console.log('====================================');
    console.log(JSON.stringify(result, null, 2));
    console.log('====================================');
  } catch (error) {
    console.error(error);
  } 

如果我在findOne里面使用raw: true,会显示角色的信息,所以我认为关联是正确的。 我非常感谢任何帮助找到我在这里缺少的东西。 谢谢

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    好吧,经过几天的努力和尝试不同的方法来解决这个问题,我的一个朋友刚刚帮助我重新开始了整个项目,遵循 Sequelize 的文档和我们之前所做的确切结构,但更简单一点,而且令人惊讶的是……奏效了。所以我想这与迁移矿石模型或其他东西有关,但我们不能真正说出来。

    【讨论】:

      猜你喜欢
      • 2016-05-11
      • 2012-02-19
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多