使用sequalize的sequalize-auto关系问题

时间:2016-11-24 12:23:28

标签: mysql node.js sequelize.js

我正在使用sequelize-auto从数据库中创建模型。但我无法使用include方法进行关系。我收到以下错误

错误:student_details_tbl(studentDetails)与user_tbl没有关联!

以下是我的模型和数据库连接。

数据库连接

var config      =   require('./config'); 
var Sequelize   =   require('sequelize');

var db          =   new Sequelize(config.dbConn.database, config.dbConn.user, config.dbConn.password,{
    dialect     :   config.dbConn.dialect,
    host        :   config.dbConn.host,
    port        :   config.dbConn.port,
    pool        :   config.dbConn.pool,
    define      :   {
        timestamps: false
    }
});

db.sync();


db.Sequelize    =   Sequelize;

module.exports  =   db;

user_tbl:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('user_tbl', {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    firstName: {
      type: DataTypes.STRING,
      allowNull: true
    },
    lastName: {
      type: DataTypes.STRING,
      allowNull: true
    },
    loginId: {
      type: DataTypes.STRING,
      allowNull: true
    },
    password: {
      type: DataTypes.STRING,
      allowNull: true
    },
    created: {
      type: DataTypes.DATE,
      allowNull: true,
      defaultValue: sequelize.literal('CURRENT_TIMESTAMP')
    },
    modified: {
      type: DataTypes.DATE,
      allowNull: true,
      defaultValue: sequelize.literal('CURRENT_TIMESTAMP')
    }
  }, {
    tableName: 'user_tbl'
  });
};

student_details_tbl:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('student_details_tbl', {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    userId: {
      type: DataTypes.INTEGER(11),
      allowNull: true,
      references: {
        model: 'user_tbl',
        key: 'id'
      }
    },
    barcode: {
      type: DataTypes.INTEGER(13),
      allowNull: false
    },
    rollNumber: {
      type: DataTypes.STRING,
      allowNull: false,
      defaultValue: ''
    },
    created: {
      type: DataTypes.DATE,
      allowNull: true,
      defaultValue: sequelize.literal('CURRENT_TIMESTAMP')
    },
    modified: {
      type: DataTypes.DATE,
      allowNull: true,
      defaultValue: sequelize.literal('CURRENT_TIMESTAMP')
    }
  }, {
    tableName: 'student_details_tbl'
  });
};

1 个答案:

答案 0 :(得分:1)

“有时您可能想要引用另一个表,而不添加任何约束或关联。在这种情况下,您可以手动将引用属性添加到模式定义中,并标记它们之间的关系。”。

因此,使用引用属性,您将不会在DataBase中创建模型关系。您应该在classMethods中使用关联,如HasOne,BelongsTo ...

http://docs.sequelizejs.com/en/latest/docs/associations/