寻找活动模型序列化程序,例如 Sequelize 的嵌套关联输出

Looking for Active Model Serializer like nested, associative output for Sequelize

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

使用 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))

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

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


非常感谢您的帮助。我正在努力避免太多的获取请求。

包含在 .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))