Reputation: 115
Is it possible with Sequelize to dynamically select a column with a variable?
For example :
I have a table (schedule) with the days as column (Monday, Tuesday, Wednesday, ...) where I store hours of work.
I would like to select the column that corresponds to the request of my client (client side I return a day (string) and with this day I must select the correct column and modify it.I can select the column with
coach.getSchedule({
attributes: [dateToLowerCase]
})
But impossible to modify, I tried this:
// schedule.set(day, hoursString)
But impossible to save, it returns an error
EDIT :
Model:
module.exports = (sequelize, DataTypes) => {
var Schedule = sequelize.define('Schedule', {
start_date: DataTypes.DATEONLY,
end_date: DataTypes.DATEONLY,
monday: DataTypes.STRING(24),
tuesday: DataTypes.STRING(24),
wednesday: DataTypes.STRING(24),
thursday: DataTypes.STRING(24),
friday: DataTypes.STRING(24),
saturday: DataTypes.STRING(24),
sunday: DataTypes.STRING(24)
}, {
freezeTableName: true
});
Schedule.associate = function (models) {
Schedule.belongsTo(models.Coach, {
foreignKey: 'fk_id_coach'
})
};
return Schedule;
};
Controller:
exports.updateCoachSchedule = (req, res) => {
const coachId = req.body.coachId
const day = req.body.day;
const indexArray = req.body.indexArray;
Coach.find({
where: {
id: coachId
}
}).then((coach) => {
if (!coach) {
return res.status(404).json({
message: "Coach inexistant"
})
}
dateToLowerCase = day.toLowerCase();;
coach.getSchedule({
attributes: [dateToLowerCase]
}).then(schedule => {
if (!schedule) {
return res.status(404).json({
message: 'Pas d\'horaire.'
})
}
const stringRetrieved = schedule.dataValues
const chainOfStringSchedule = stringRetrieved[Object.keys(schedule.dataValues)[0]]
hours = transformChainSchedule(chainOfStringSchedule)
for (var i = 0; i < hours.length; i++) {
hours[i] = indexArray.includes(i) ? "1" : "0";
}
const hoursString = hours.join("")
schedule.set(day, hoursString).save().then(() => {
res.status(200).json({
message: "Schedule modified !",
schedule
})
}).catch(err => {
res.json({
err
})
})
})
.catch(err => {
res.status(500).json({
error: err
})
})
})
}
Thank you !
Upvotes: 0
Views: 2388
Reputation: 58553
Instead of this line
schedule.set(day, hoursString).save().then()
Use the below one , this will solve your issue ,
let updateData = {};
updateData[day] = hoursString;
schedule.update(updateData).then()
Upvotes: 1