Using the Sequelize ORM I am trying to update the field level_id where this field has a foreign key to the field Level in another table called level_tbl.
select * from level_tbl;
+----------+----------+
| level_id | Level |
+----------+----------+
| 1 | Higher |
| 2 | Ordinary |
+----------+----------+
My update task looks like this, and as you can see I am trying to get a raw sql query to work as a literal with Sequelize.
//Update task
router.put("/task/:id", (req, res) => {
if (!req.body) {
res.status(400)
res.json({
error: "Bad Data....!"
})
} else {
Task.update({
Level: req.body.Level,
Level_id: [sequelize.literal("SELECT level_id FROM level_tbl WHERE Level = 'Ordinary'")],
Year: req.body.Year,
Question: req.body.Question,
Answer: req.body.Answer,
Topic: req.body.Topic,
Sub_topic: req.body.Sub_topic,
Question_type: req.body.Question_type,
Marks: req.body.Marks,
Question_number: req.body.Question_number,
Part: req.body.Part,
Sub_part: req.body.Sub_part
}, {
where: {
id: req.params.id
}
})
.then(() => {
res.send("Task Updated")
})
.error(err => res.send(err))
}
})
What would be the correct syntax for this line?
Level_id: [sequelize.literal("SELECT level_id FROM level_tbl WHERE Level = 'Ordinary'")],
The issue is that I already have imported a model and have access to the global Sequelize instance. Therefore example in the documentation don't apply this way, i.e.,
order: sequelize.literal('max(age) DESC')
From https://sequelize.org/master/manual/querying.html
and also,
https://github.com/sequelize/sequelize/issues/9410#issuecomment-387141567
My Task.js where the model is defined is as follows,
const Sequelize = require("sequelize")
const db = require("../database/db.js")
module.exports = db.sequelize.define(
"physics_tbls", {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
Level: {
type: Sequelize.STRING
},
Level_id: {
type: Sequelize.INTEGER
},
Year: {
type: Sequelize.INTEGER
},
.........
}, {
timestamps: false
}
)
I am using a MEVN stack -> MySQL, Express.js, Vue.js and Node.js
Any help would be greatly appreciated,
Thanks,
I needed to require Sequelize again in tasks.js, the file the defines the express routes. It wasn't enough just to require Task.js although Task.js does itself require sequelize.
const Sequelize = require('sequelize')
var express = require("express")
var router = express.Router()
const Task = require("../model/Task")
Also brackets needed around the query and inside the double quotes,
Level_id: Sequelize.literal("(SELECT level_id FROM level_tbl WHERE Level = 'Higher')"),
I am using sequelize 6.3 and raw query on where
is no longer supported
I used this syntax :
where: sequelize.where(sequelize.col("table.column"), "=", "yourvalue")
and it worked
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With