Reputation: 5914
I have received a bizarre association error after running a query with a table join that has a one-to-many relationship with the primary table being queried. Despite having the association set up and relationship displayed in my database as it is displayed in my model, I still receive an error. What am I missing that could be causing this? Note that the request table was created with a migration file using the cli. Could this be the key issue?
Here is the error:
Unhandled rejection Error: user is not associated to request!
Here is my query:
models.Request.findAll({
include: [{
model: models.User
}],
where: {
$or: [{requester: req.user.userId}, {receiver: req.user.userId}]
}
});
Here is the user table, where the one-to-many join exists:
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;
}
Here is the request table (This table was originally migrated with the 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 (where the association is created):
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;
Screenshot of relationship on request table:
Upvotes: 0
Views: 1186
Reputation: 2775
In order to get User
using Request
model, you should define association Request->belongsTo->User
. Existed relation User->hasMany->Request
tells us that you can get Requests
through User
model, not reversively
Upvotes: 1