我正在尝试将数字“2”连接到有时可能为 null
的行中的值。其他时候,它将是一个字符串。我正在使用 Sequelize.fn 方法连接“2”,但在值为 null 的情况下,它不会执行任何操作。具体来说,它保持为空并且不会像我预期的那样变成“2”。如果该值不为空,而是一个字符串,则它有效。我已经通过检查数据库本身中的结果值来确认这一点。还有另一种方法可以使用 Sequelize 连接到空值吗?
这是尝试连接到 null 的简化代码:
mysql.determineDatabase('db-name', 'table-name').then((database) => {
database.sequelize.sync().then(() => {
database.table_name.update({
code: Sequelize.fn('concat', Sequelize.col('code'), 2)
}, { where: { code: req.body.code }
}).then((result) => {
res.status(200).send({ ... });
}).catch((error) => {
res.status(400).send(error);
});
});
});
最佳答案
以防万一有人偶然发现这个问题并需要答案,我最终这样做而不是尝试使用 sql 函数:
mysql.determineDatabase('db-name', 'table-name').then((database) => {
database.sequelize.sync().then(() => {
database.table_name.findAll({ where: { code: req.body.code } })
.then((response) => {
const code = response[0].dataValues.code;
const concatenatedCode = code === null ? 2 : `${code}2`;
database.table_name.update({
code: concatenatedCode
}, { where: { code: req.body.code }
}).then((result) => {
res.status(200).send({ ... });
}).catch((error) => {
res.status(400).send(error);
});
});
});
});
基本上,我只是通过.findAll()
获取之前的值。如果返回值为 null
,我将其替换为 2,否则,我连接 2。
关于mysql - Sequelize/Node – 连接到空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48546246/