【问题标题】:Looking for Active Model Serializer like nested, associative output for Sequelize寻找活动模型序列化器,如 Sequelize 的嵌套关联输出
【发布时间】:2019-04-26 20:20:26
【问题描述】:

如果我的研究不足,请原谅我。一个多小时以来,我一直在阅读文档并搜索该站点,但无济于事,我真的可以使用一些专家的帮助。

使用 Rails,我可以使用 Active Model Serializer 发送与查询集关联的数据。例如,假设我有用户,用户有很多帖子。假设我想要如下所示的输出:

[
- {
id: 1,
username: "Matz",
posts: [
   - {
   id: 35,
   title: "Hello world",
   content_body: "This is the content of my post."
},
-{
   id: 98,
   title: "Foo Bar",
   content_body: "This is the content of my other post."
}]},
]

使用 Active Model Serializer 这将是微不足道的。我希望使用 Sequelize 获得类似的输出。

我的关联工作正常,例如,我可以这样做:

return db.Users.findByPk(user_id)
    .then(user => user.getPosts())
    .then(posts => res.send(posts))

* 编辑添加 * 一个问题是,我真正想做的是将包含放在 user.getPosts() 中,例如。

我需要的是获取属于用户的帖子,然后获取这些帖子所属的标签。


非常感谢您的帮助。我试图避免过多的获取请求。

【问题讨论】:

  • 您可以在查询中使用include:docs.sequelizejs.com/manual/…
  • 谢谢。我一定是做错了什么,因为这对我不起作用。
  • 一个问题是我需要 .findByPk 为用户,然后执行类似 user.getPosts() 并在 getPosts() 中包含。这似乎不起作用。

标签: javascript node.js sequelize.js active-model-serializers


【解决方案1】:

包含在 .getPosts 中确实有效。我没有完全理解这些文档。

因为我在我的 app.js 中导入了模型:

const db = require('./models');

我需要写以下内容:

return db.Users.findByPk(user_id)
    .then(user => user.getPosts({
      include: [{
        model: db.Tags
     }]
}))
    .then(posts => res.send(posts))

【讨论】:

    猜你喜欢
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 2016-09-03
    相关资源
    最近更新 更多