首页 文章

Sails和Sequelize,没有添加到数据库的关联

提问于
浏览
1

这就是我的模型在帆中的结构:

myapp
--api
----controllers
----models
-----User.js
------Role.js

user.js的

module.exports = {
 attributes:{
   id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true
   },
   username: {
       type: Sequelize.STRING,
   },
   password: {
       type: Sequelize.STRING,
   }
 },
 associations: function() {
   User.hasOne(Role, {foreignKey: 'id', as: 'role' });
 }
};

Role.js

module.exports = {
 attributes:{
   id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true
   },
   name: {
       type: Sequelize.STRING,
   }
 }
};

在风帆升级之后,在postgresql中我有用户表,其中包含id,username,password,createdat和updatedat角色表,其中包含id,name,createdat和updatedat . 用户表中的角色没有foreignKey .

我怎么解决这个问题?我正在使用sails-hook-sequelize和sails-hook-sequelize-blueprints,这是否会因为它们而发生?

谢谢!

编辑:

正确的方法是:

module.exports = {
 attributes:{
   id: {
      type: Sequelize.INTEGER,
      primaryKey: true,
      autoIncrement: true
   },
   username: {
       type: Sequelize.STRING,
   },
   password: {
       type: Sequelize.STRING,
   }
 },
 associations: function() {
     User.hasOne(Role, {
      as : 'role',
      foreignKey: {
        name: 'roleId',
        allowNull: false
      }
    });
 }
};

1 回答

  • 1

    默认情况下会添加 createdAtupdatedAt 列,除非您将 timestamps 选项设置为false . 见docs .

    要添加外键约束,需要为Roles模型定义associations .

相关问题