永不创建结局关联

时间:2018-10-24 07:46:35

标签: mysql foreign-keys associations sequelize.js

我已经努力了一个星期,试图修复序列化关联。我在网上搜索了一种解决方案,但听起来似乎没有人遇到与我所遇到的问题完全相同的问题。 当我在模型中添加关联时,根本不会创建关联。 elementsTo永远不会将外键字段添加到相关表中。我已详细分享了我的架构,希望有人在那里 将帮助我解决问题。我也曾尝试在模型和迁移中直接添加前导键,但没有成功。

我有4个模型:用户,角色,权限和发布。一个用户有很多帖子,一个用户通过 RoleUser 关联表属于ToMany 角色,一个角色通过RoleUser关联表 belongsToMany 用户。权限属于ToMany 角色通过PermissionRol e连接表。

//User Model
'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    id: {type:DataTypes.UUID,allowNull:false,unique:true,primaryKey:true},
    UserName: {type:DataTypes.STRING,unique:true,allowNull:false},
    Email: {type:DataTypes.STRING,allowNull:false,unique:true,validate: { isEmail: {msg: "Invalid Email"} }},
    Password: {type:DataTypes.STRING,allowNull:false}

  }, {});
  User.associate = function(models) {
    User.hasMany(models.Post,
        {
            foreignKey:'UserId',
            as:'posts',
            sourceKey:'id'
        }),

      User.belongsToMany(models.Role,
            {
        through: 'RoleUser',
        foreignkey:'UserId'

    })


 };
  return User;
};

//Post model

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Post = sequelize.define('Post', {
    id: {type:DataTypes.UUID,allowNull:false,unique:true,primaryKey:true},
    Title: DataTypes.STRING,
    Post: DataTypes.TEXT
  }, {});
  Post.associate = function(models) {
 Post.belongTo(models.User,
    {
        foreignKey:'UserId',
        sourceKey:'id'
    })


  };
  return Post;
};

//Role Model

'use strict';
module.exports = (sequelize, DataTypes) => {
  const RoleUser = sequelize.define('RoleUser', {
    RoleId: {type:DataTypes.UUID,allowNull:false,primaryKey:true},
    UserId: {type:DataTypes.UUID,allowNull:false,primaryKey:true},

  }, {});
  RoleUser.associate = function(models) {
    // associations can be defined here

    RoleUser.belongsTo(models.User,{foreignKey:'UserId'}),
    RoleUser.belongsTo(models.Role,{foreignKey:'RoleId'})
  };
  return RoleUser;
};

//Permission Model

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Permission = sequelize.define('Permission', {
    id: {type:DataTypes.UUID,allowNull:false,unique:true,primaryKey:true},
    Name: DataTypes.STRING,
    Description: DataTypes.STRING
  }, {});
  Permission.associate = function(models) {
    // associations can be defined here

    Permission.belongsToMany(models.Role,
        {
            through:'PermissionRole',
            foreignKey:'PermissionId'

        })

  };
  return Permission;
};

表迁移

//users

'use strict';
const uuidv4 = require('uuid/v4');

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        primaryKey: true,
        type: Sequelize.UUID
        defaultValue:uuidv4()
      },
      UserName: {
        type: Sequelize.STRING
      },

      Email: {
        type: Sequelize.STRING
      },
      Password: {
        type: Sequelize.STRING
      },

      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Users');
  }
};

//Post migration

'use strict';
const uuidv4 = require('uuid/v4');
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('posts', {
      id: {
        allowNull: false,
        primaryKey: true,
        type: Sequelize.UUID,
        defaultValue:uuidv4()
      },
      Title: {
        type: Sequelize.STRING
      },
      Post: {
        type: Sequelize.Text
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('CourseCategories');
  }
};

//Role migration

'use strict';
const uuidv4 = require('uuid/v4');
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Roles', {
      id: {
        allowNull: false,
        primaryKey: true,
        type: Sequelize.UUID,
        defaultValue:uuidv4()
      },
      Name: {
        type: Sequelize.STRING
      },
      Description: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Roles');
  }
};

//Permission migration

'use strict';
const uuidv4 = require('uuid/v4');

module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Permissions', {
      id: {
        allowNull: false,
        primaryKey: true,
        type: Sequelize.UUID,
        defaultValue:uuidv4()
      },
      Name: {
        type: Sequelize.STRING
      },
      Description: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Permissions');
  }
};

运行迁移后,将按预期创建所有表。甚至连表中的角色用户和权限都是由sequelize创建的。

但是,没有添加外键。例如,posts表没有预期的UserId外键

当我在PhpMyAdmin关系视图中查看表时,表之间不存在外键或关系。

当我尝试查询和列出具有与每个角色相关的权限的角色时,如下所示,我收到此错误:

 SequelizeEagerLoadingError: Permission is not associated to Role!

这是我的查询:

exports.rolesWithPermissions = function(req, res){
Role.findAll({
  include:[{model:Permission}]
}).then((roleperms)=>{
  return res.json({status:200,roleperms:roleperms});
}).catch((error)=>{
  console.log(error);
  return res.send({error:error.error});
});

};

在获取带有帖子的用户时,出现类似的错误。简而言之,永远不会创建关系(关联)。我在 sequelize版本4.31.2 中使用mysql方言。甚至我尝试过使用Sqlite都具有相同的结果。

我也尝试过重新安装sequelize,但没有运气。我做错了什么,请帮忙。

0 个答案:

没有答案