负载包括现有模型

Load includes on existing model

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

但是:

  1. 我对包含的扩展是通过 url 参数的动态 属性,因此无法提前知道它们。
  2. 如果我 return 以上内容,您将不会在响应中看到 "thing"。我需要它作为原始实例的一部分很好地构建。

.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 for some documentation. See here


更新:给定实例,如何获取关联模型?

为此只需使用自动生成的 "getAssociation" getter 函数,例如:

function find_associations_of_instance(instance) {
  return instance.getDetails();
}

我已经更新了脚本以包含此作为示例。有关这些函数的更多信息,请参阅 SequelizeJS docs.