'using replacements with sequelize.literal()
I'm trying to use replacements with sequelize.literal() query.
router.get('/posts/testapik', function(req, res)
{
const user_id = req.session.user_id;
const status ="accept"
Posts.findAll({include:[{ model: Likes},{ model: Comments},{ model: Users}],
where:{user_id:{[Op.in]:[sequelize.literal('SELECT `Follows`.receiver_id FROM `follows` AS `Follows` WHERE `Follows`.user_id=? and `Follows`.status=?',{ replacements: [user_id,status], type: sequelize.QueryTypes.SELECT })]}}
})
.then(users =>
{
res.send(users);
})
});
But it returns following error
original:
{ Error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '? and `Follows`.status=?)' at line 1
Solution 1:[1]
For replacements, you have to set the replacements property inside the query object.
router.get("/posts/testapik", function (req, res) {
const user_id = req.session.user_id;
const status = "accept";
Posts.findAll({
include: [{ model: Likes }, { model: Comments }, { model: Users }],
replacements: [user_id, status],
where: {
user_id: {
[Op.in]: [
sequelize.literal(
"SELECT `Follows`.receiver_id FROM `follows` AS `Follows` WHERE `Follows`.user_id=? and `Follows`.status=?"
),
],
},
},
}).then((users) => {
res.send(users);
});
});
Solution 2:[2]
For replacements on a raw query you have to write the variable name inside the query with this format: :userIdReplacement.
const query = '(SELECT `Follows`.receiver_id FROM `follows` AS `Follows` WHERE `Follows`.user_id= :userIdReplacement and `Follows`.status="accept")';
db.sequelize.query(query, { replacements: { userIdReplacement : user_id }});
If you have more than one replacement just put it inside the replacements object seperate it by commas.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | quinn |
| Solution 2 | Ellebkey |
