.hasMany称之为“Sequelize.Model”的子类

时间:2018-05-31 02:35:41

标签: mysql node.js orm sequelize.js node-modules

我试图在2个型号之间引用外键。 但是我收到了这个错误:

throw new Error(this.name + '.hasMany called with something that\'s not a subclass of Sequelize.Model');       ^

错误:user_relation.hasMany调用的东西不是Sequelize.Model的子类

squelize.js

const Sequelize = require('sequelize');
const config = require('./default.config')
const sequelize = new Sequelize(config.database, config.user, config.password, {
  host: config.host,
  port: config.port,
  dialect: 'mysql',
  timezone: config.timezone,//东八区
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  }
});

sequelize
  .sync()
  .then(err => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

module.exports = sequelize;

用户模型

const sequelize = require(' sequelize');     const Model = require(' ../../ config / squelize');

const Admin = Model.define('admin', {
  username : {type : sequelize.STRING, allowNull : false},//用户名
  password : {type : sequelize.STRING, allowNull : false},//密码
  details : {type : sequelize.STRING, allowNull : true},//简介
  head_thumb : {type : sequelize.STRING, allowNull : true},//头像
  gender : {type : sequelize.STRING, allowNull : true},//性别
  nickname : {type : sequelize.STRING, allowNull : true},//昵称
  userid : {type : sequelize.INTEGER, autoIncrement : true, primaryKey : true}//用户userid
}, {
  freezeTableName:true
})

module.exports = Admin;

admin_relation.js

var Sequelize = require('sequelize');
const Model = require('../../config/squelize');
const Admin = require('./admin.model')

var user_relation = Model.define('user_relation', {
    id : {type : Sequelize.INTEGER, autoIncrement : true, primaryKey : true},
    userid : {type : Sequelize.STRING, allowNull : false},//用户id
    frendid : {type : Sequelize.STRING, allowNull : false}//朋友id
},{
    timestamps:false,
    freezeTableName:true,
});
user_relation.hasMany(Admin,{as:'admin',foreignKey:'userid'})

module.exports = user_relation;

是否有人看到过这样的错误?我搜索了几天没有任何问题,如果有人可以帮助我真的很感激,

谢谢!

2 个答案:

答案 0 :(得分:0)

我认为您正在尝试在Adminty模型中的userid键的user_relation模型中维护外键。如果是这样,则必须关联定义sourceKey和targetKey。

使用相同的数据类型定义sourceKey和targetKey。

在管理模式中

Admin.belongsTo(user_relation, {
    foreignKey: 'userid',
    targetKey: 'userid'
});

在user_relation模型中

user_relation.hasMany(Admin, {
    as: 'admin',
    foreignKey: 'userid',
    sourceKey: 'userid'
});

答案 1 :(得分:0)

如果存在许多场景,最好创建一个新模型,并在该模型中添加关系。否则,将关系放在一侧。

Admin.belongsTo(User);

在管理员方面,您也可以放置

User.hasMany(Admin);