我有这种奇怪的行为 . 我有一个用户模型和一个客户端模型 . 用户有很多客户端 . 我正在使用这个文档:http://docs.sequelizejs.com/manual/tutorial/associations.html
当我运行服务器时,Sequelize抛出TypeError:User.hasMany不是一个函数
Node version: 8.9.1
Dialect: postgres
Database version: Postgres 10
Sequelize version: 4.22.15
以下文件都在同一文件夹中
user.js模型
const Sequelize = require('sequelize');
const db = require('../index.js'); //This is an instance of new Sequelize(...)
const tableName = 'users';
const User = db.define('user', {
firstName: {
type: Sequelize.STRING(50),
allowNull: false,
validate: {
notEmpty: true
}
},
lastName: {
type: Sequelize.STRING(50),
allowNull: false,
validate: {
notEmpty: true
}
},
username: { //Username will be the email
type: Sequelize.STRING(80),
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password: {
type: Sequelize.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
isAdmin: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
},
isActive: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
}
}, { tableName });
module.exports = User;
client.js模型
'use strict'
const Sequelize = require('sequelize');
const db = require('../index.js');
const instanceMethods = {
toJSON() {
const values = Object.assign({}, this.get());
return values;
},
};
const Client = db.define('clients', {
ibid: {
type: Sequelize.BIGINT,
allowNull: true,
defaultValue: null
},
firstName: {
type: Sequelize.STRING(50),
allowNull: false,
validate: {
notEmpty: true
}
},
lastName: {
type: Sequelize.STRING(50),
allowNull: false,
validate: {
notEmpty: true
}
},
agreementSigned: {
type: Sequelize.BOOLEAN,
allowNull: false,
defaultValue: false
},
totalBalance: {
type: Sequelize.DECIMAL(11,2),
allowNull: true,
defaultValue: null
},
currentAllocation: {
type: Sequelize.STRING,
allowNull: true,
defaultValue: null
}
}, { instanceMethods });
module.exports = Client;
index.js模型
'use strict';
const User = require('./user')
const Client = require('./client');
User.hasMany(Client);
Client.belongsTo(User);
module.exports = {User, Client};
1 回答
在index.js中,您尚未导出已初始化的新sequelize实例,因此client.js和user.js无法使用它! define函数适用于您创建的sequelize实例对象!
此外,项目中存在循环依赖,这可能会产生问题!
我尝试了你的代码并改变了结构,它现在正常工作!可能还有其他结构,但这个对我有用!
1)不要在index.js中创建一个新的sequelize实例,而是创建另一个文件,作为sequelize实例的初始化!
sequelize_index.js(我使用此文件创建基本实例,然后在客户端和用户模型中使用此基本实例)
2)client.js看起来像这样!
3)User.js
4)index.js
运行index.js后,将创建数据库!