加载包含在现有模型

时间:2015-11-20 12:21:00

标签: javascript node.js sequelize.js

我试图在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;
    });

可是:

  1. 我对包含的扩展是一个通过url参数提供的动态属性,因此它们不会提前知道。
  2. 我回复上面你不会看到""在回应中。我需要它作为原始实例的一部分很好地构建。
  3. .with('thing', 'other.thing');符号这样的东西会很好。或者在续集.with({include: ...});.include([{model: ...}]);

    的情况下

1 个答案:

答案 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