我试图在sequelize中加载现有模型的包含。在express中,我们预先检查模型以查看它们是否存在于中间件中。
因此,一旦我们进入实际的"控制器"我们想在传入的现有模型上运行一些包含。
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');
符号这样的东西会很好。或者在续集.with({include: ...});
或.include([{model: ...}]);
答案 0 :(得分:0)
如果变量req.models.item
已经是Instance但没有其他相关实例("包含"),那么您可以使用以下代码包含它们:
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"吸气功能,例如:
function find_associations_of_instance(instance) {
return instance.getDetails();
}
我已更新脚本以包含此示例。有关这些功能的更多信息,请参阅SequelizeJS docs。