续集多对多仍然没有关联

时间:2018-03-16 23:09:39

标签: sequelize.js

所以我对这个问题已经过了一个多星期但仍然遇到同样的错误:SequelizeEagerLoadingError: roles is not associated to users!

我希望拥有可以拥有多个用户的多个角色和角色的用户。表名背后的想法并不重要 - 我想学习如何做N:M协会(或协会)。

我的模特: 用户:

export const User = sequelize.define('users', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  email: {
    type: Sequelize.STRING,
    unique: true
  },
  password: Sequelize.STRING,
  name: Sequelize.STRING,
  lastName: Sequelize.STRING,
  address: Sequelize.STRING,
  phoneNumber: Sequelize.STRING,
  position: Sequelize.STRING,
  department: Sequelize.STRING,
  createdAt: Sequelize.DATE,
  updatedAt: Sequelize.DATE
}, {
  tableName: 'users',
  timestamps: true
});

作用:

export const Role = sequelize.define('roles', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  roleName: {
    type: Sequelize.STRING,
    unique: true
  }
}, {
  tableName: 'roles',
  timestamps: true
});

的UserRole:

export const UserRole = sequelize.define('users_role', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  role_id: {
    type: DataTypes.INTEGER,
    unique: 'user_role_roleable'
  },
  user_id: {
    type: DataTypes.INTEGER
  },
  roleable: {
    type: DataTypes.STRING,
    unique: 'user_role_roleable'
  },
  roleable_id: {
    type: DataTypes.INTEGER,
    unique: 'user_role_roleable'
  }
}, {
  tableName: 'users_roles'
});

和协会:

/*
User.belongsToMany(Role, {
  as: 'u',
  through: 'users_roles',
  constraints: false,
  foreignKey: 'roleable_id'
});

Role.belongsToMany(User, {
  as: 'r',
  through: 'users_roles',
  constraints: false,
  foreignKey: 'role_id'
});*/
User.belongsToMany(Role, {through: UserRole});
Role.belongsToMany(User, {through: UserRole});

我这样查询:

User.findAll({ include: [{model: Role}]}).then(r => console.log(r));

我尝试使用和不使用别名(需要将其包含在include中),尝试了与此问题几乎完全相同的问题的其他示例,但最终仍然存在错误。我错过了什么?

我正在使用"sequelize": "^4.32.2", "sequelize-cli": "^4.0.0",表达和打字稿。

0 个答案:

没有答案