我正在尝试在 Sequelize 中的现有模型上加载包含。在 express 中,我们预先检查模型以查看它们是否存在于中间件中。
因此,一旦我们进入实际的“ Controller ”,我们希望在传入的现有模型上运行一些包含。
req.models.item.incude([
{model: Post, as: 'posts'}
])
有什么办法可以做到这一点吗?
编辑:
我知道我们可以做这样的事情。
return req.models.item.getThing()
.then(function (thing) {
req.models.item.thing = thing;
return req.models.item;
});
但:
像
.with('thing', 'other.thing');
符号这样的东西会很好。或者在 Sequelize .with({include: ...});
或 .include([{model: ...}]);
的情况下
最佳答案
如果变量 req.models.item
已经是 Instance 但没有其他相关实例(“includes”),那么您可以使用类似以下代码的内容包含它们:
Item.findAll({
where: req.models.item.where(),
include: [{
model: SomeAssociateModel,
}]
})
.then(function(itemWithAssoc) {
// itemWithAssoc is an Instance for the same DB record as item, but with its associations
});
有关一些文档,请参阅 here。请参阅 here 以获取脚本演示。
更新:给定实例,我如何获取相关模型?
为此,只需使用自动生成的“getAssociation”getter 函数,例如:
function find_associations_of_instance(instance) {
return instance.getDetails();
}
我已经更新了脚本以将其作为示例包含在内。有关这些函数的更多信息,请参阅 SequelizeJS docs 。
关于javascript - 负载包括在现有模型上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33826607/