gpt4 book ai didi

javascript - 负载包括在现有模型上

转载 作者:行者123 更新时间:2023-12-03 22:42:28 25 4
gpt4 key购买 nike

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

但:
  • 我对包含的扩展是一个通过 url 参数来的动态属性,所以他们不知道提前。
  • 如果我返回上述内容,您将不会在响应中看到“东西”。我需要它作为原始实例的一部分很好地构建。

  • .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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com