在使用与正在查询的主表具有一对多关系的表连接运行查询后,我收到了一个奇怪的关联错误。尽管我的数据库中显示关联设置和关系显示在我的模型中,但仍然收到错误。我错过了什么可能导致这种情况?请注意,请求表是使用cli使用迁移文件创建的。这可能是关键问题吗?
这是错误:
Unhandled rejection Error: user is not associated to request!
这是我的问题:
models.Request.findAll({
include: [{
model: models.User
}],
where: {
$or: [{requester: req.user.userId}, {receiver: req.user.userId}]
}
});
以下是用户表,其中存在一对多联接:
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('user', {
userId: {
type: DataTypes.INTEGER,
field:'user_id',
autoIncrement: true,
primaryKey: true
},
firstName: {
type: DataTypes.STRING,
field: 'first_name'
},
lastName: {
type: DataTypes.STRING,
field: 'last_name'
},
email: {
type: DataTypes.STRING,
isEmail: true,
unique: true,
set: function(val) {
this.setDataValue('email', val.toLowerCase());
}
},
password: DataTypes.STRING,
organizationId: {
type: DataTypes.INTEGER,
field: 'organization_id',
allowNull: true
},
teamId: {
type: DataTypes.INTEGER,
field: 'team_id',
allowNull: true
},
}, {
underscored: true,
freezeTableName: true,
classMethods: {
associate: function(db) {
User.hasMany(db.Request, { foreignKey: 'requester'});
},
});
return User;
}
以下是请求表(此表最初是使用cli迁移的):
module.exports = function(sequelize, DataTypes) {
var path = require('path');
var moment = require('moment');
var current = new Date();
var day = ("0" + current.getDate()).slice(-2);
var month = ("0" + (current.getMonth() + 1)).slice(-2);
var today = current.getFullYear() + '-' + (month) + '-' + (day);
var Request = sequelize.define('request', {
requestId: {
type: DataTypes.INTEGER,
field: 'request_id',
autoIncrement: true,
primaryKey: true
},
requestDate: {
type: DataTypes.DATE,
field: 'request_date',
isDate: true,
allowNull: false,
defaultValue: today
},
requester: {
type: DataTypes.INTEGER,
field: 'requester',
references: {
model: 'user',
key: 'user_id'
},
onUpdate: 'cascade',
onDelete: 'cascade'
},
receiver: {
type: DataTypes.INTEGER,
field: 'receiver'
},
},
{
underscored: true,
freezeTableName: true,
});
return Request;
}
db-index(创建关联的位置):
var Sequelize = require('sequelize');
var path = require('path');
var sequelize = new Sequelize(process.env.LOCAL_DATABASE || process.env.RDS_DATABASE,
process.env.LOCAL_USERNAME || process.env.RDS_USERNAME,
process.env.LOCAL_PASSWORD || process.env.RDS_PASSWORD, {
host: process.env.RDS_HOSTNAME || 'localhost',
port: process.env.RDS_PORT || '3306',
dialect: 'mysql',
timezone: 'America/New_York'
});
sequelize.authenticate().then(function(err) {
if (!!err) {
console.log('Unable to connect to the database:', err)
} else {
console.log('Connection has been established successfully.')
}
});
var db = {}
db.User = sequelize.import(__dirname + "/user");
db.Request = sequelize.import(__dirname + "/request");
db.User.associate(db);
db.sequelize = sequelize;
db.Sequelize = Sequelize;
sequelize.sync();
module.exports = db;
请求表上关系的屏幕截图:
答案 0 :(得分:1)
要使用User
模型获取Request
,您应该定义关联Request->belongsTo->User
。已存在的关系User->hasMany->Request
告诉我们您可以Requests
通过User
模型,而不是反转