问题
I am trying to join two tables, but getting an error message message: "user is not associated to availability!"
.I have given the association in below user and availability models as suggested by someone.
I would like to get data from following columns in tables user and availability
for current date (today) alone.
data from photo, position
columns in user table.
data from dailystatus
column in Availability table.
One thing I have noticed that if I remove the include: [{..
part then it will start displaying data in front end.
app.get('/service/availability', async (req, res) => {
try {
var today = moment().format('YYYY-MM-DD HH:mm:ss');
const dailyStatus = await Availability.findAll({
where: {
dailystatus: ['in', 'out']
},
include: [{
model: UserModel,
attributes: ['photo', 'position'],
where :{
createdAt : today
}
}],
});
res.status(200).json({ dailyStatus });
} catch (e) {
res.status(500).json({ message: e.message });
}
});
availability.js
module.exports = (sequelize, DataTypes) => {
const availability = sequelize.define('availability', {
email: {
type: DataTypes.STRING(100),
allowNull: false
},
dailystatus: {
type: DataTypes.STRING(50),
allowNull: false
},
user_id: {
type: DataTypes.INTEGER(18)
},
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
}
}, {
timestamps: false,
tableName: 'availability'
});
availability.associate = function (models) {
// associations can be defined here
availability.belongsTo(models.user, {
foreignKey: "user_id",
onDelete: "CASCADE"
});
};
return availability;
}
user.js
'use strict';
module.exports = (sequelize, DataTypes) => {
const user = sequelize.define('user', {
name: {
type: DataTypes.STRING(30),
allowNull: false
},
email: {
type: DataTypes.STRING(100),
allowNull: false
},
phonenumber: {
type: DataTypes.STRING(50),
},
id: {
type: DataTypes.INTEGER(10).UNSIGNED,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
password: {
type: DataTypes.STRING(50),
allowNull: false
},
privilege: {
type: DataTypes.STRING(100),
},
photo: {
type: DataTypes.STRING(300),
},
position: {
type: DataTypes.STRING(100),
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
}
}, {
timestamps: false,
tableName: 'user'
});
user.associate = function (models) {
// associations can be defined here
user.hasOne(models.availability, {
foreignKey: "user_id",
onDelete: "CASCADE"
});
};
return user;
};
user
table:
availability
table :
来源:https://stackoverflow.com/questions/62525061/getting-an-association-error-user-is-not-associated-to-availability