如果您只想在 SQL 查询中插入一个“标签”,您可以使用Sequelize.literal() 将文字字符串传递给查询生成器。将此添加到 options.attributes.include 将添加它,但是它还需要一个别名,因此您还必须传递某种值。
Model.findById(id, {
attributes: {
include: [
[Sequelize.literal('/* your comment */ 1'), 'an_alias'],
],
},
});
这会产生类似于
的SQL
SELECT `model`.`id`, /* your comment */ 1 as `an_alias`
FROM `model` as `model`
WHERE `model`.`id` = ???
我尝试了一点自动化,它可能超出了这个答案的范围,但是您可以在使用 new Sequelize() 创建连接之前修改 Sequelize.Model.prototype 以调整方法的处理。您需要对所有要“标记”的方法执行此操作。
// alias findById() so we can call it once we fiddle with the input
Sequelize.Model.prototype.findById_untagged = Sequelize.Model.prototype.findById;
// override the findbyId() method so we can intercept the options.
Sequelize.Model.prototype.findById = function findById(id, options) {
// get the caller somehow (I was having trouble accessing the call stack properly)
const caller = ???;
// you need to make sure it's defined and you aren't overriding settings, etc
options.attributes.include.push([Sequelize.literal('/* your comment */ 1'), 'an_alias']);
// pass it off to the aliased method to continue as normal
return this.findById_untagged(id, options);
}
// create the connection
const connection = new Sequelize(...);
注意:可能无法自动执行此操作,因为 Sequelize 具有 use strict,因此无法访问 arguments.caller 和 arguments.callee 属性。
第二个注意事项:如果您不关心修改 Sequelize.Model 原型,您还可以抽象您对 Sequelize 方法的调用并在那里调整选项。
function Wrapper(model) {
return {
findById(id, options) {
// do your stuff
return model.findById(id, options);
},
};
}
Wrapper(Model).findById(id, options);
第三条注意:您还可以提交拉取请求以将此功能添加到Sequelize 下的新选项值下,例如在查询末尾添加的options.comment。