【问题标题】:second level include using sequelize第二级包括使用续集
【发布时间】:2020-11-12 19:52:38
【问题描述】:

如果用户可以有很多帖子,每个帖子可以有很多图片,这是否意味着用户和图片是关联的?因为目前我正在尝试为每个用户显示帖子,并且对于我想使用上述方法将图像显示为 url 和 thumbnailurl 的帖子。我不断收到 Post_Image 未与用户关联的错误。

我目前正在尝试此代码,但我不断收到错误无法读取属性映射。

router.get("/posts", auth, (req, res) => {

let { id } = req.user;
User.findByPk(id, {
 include: [
  {
    model: Post,
    include: [{ model: Post_Image, attributes: ["id", "images"] }],
  },
],
}).then((post) => {
if (!post)
  return res.status(404).send();

const baseUrl = config.get("assetsBaseUrl");

const plainPost = post.get({ plain: true });
const { Post_Images, ...postAttributes } = plainPost;
const IMAGES = Post_Images.map((postImage) => ({
  url: `${baseUrl}${postImage.images}_full.jpg`,
  thumbnailUrl: `${baseUrl}${postImage.images}_thumb.jpg`,
}));

res.send({ ...postAttributes, images: IMAGES });
 });
 });

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    在这种情况下,它类似于处理多个帖子,如 my previous answer

    区别在于在哪里调用get({ plain: true })

    User.findByPk(id, {
     include: [
      {
        model: Post,
        include: [{ model: Post_Image, attributes: ["id", "images"] }],
      },
    ],
    }).then((user) => { // we got a user here and not a post or posts
    if (!user)
      return res.status(404).send();
    
    const baseUrl = config.get("assetsBaseUrl");
    
    const plainUser = user.get({ plain: true })
    const resultPosts = []
    for (const post of plainUser.Posts) {
      const { Post_Images, ...postAttributes } = post
      const IMAGES = Post_Images.map((postImage) => ({
        url: `${baseUrl}${postImage.images}_full.jpg`,
        thumbnailUrl: `${baseUrl}${postImage.images}_thumb.jpg`,
      }));
      console.log(IMAGES)
      resultPosts.push({
        ...postAttributes,
        images: IMAGES
      })
    }
    
    res.send(resultPosts);
    

    【讨论】:

    • 为什么我使用findByPk时处理多个调用是一样的?
    • 最初您询问了 Post.findAll 获得的 Posts 数组。如果您在include 选项中指定了Posts,则与从用户模型实例中获取Posts 数组相同
    • 好的,现在我明白为什么了,因为我正在尝试获取该用户的所有帖子,所以它与 findAll 相同,再次感谢您
    • 我有一个关于这个帖子stackoverflow.com/questions/64747164/…的问题,因为现在用户与帖子相关联我如何将用户表中的userId链接到帖子表中的帖子?
    • 嗨,Anatoly,我有一个关于你对这篇帖子的解决方案stackoverflow.com/questions/64747164/… 的问题。那么现在我的用户模型与我的 Post 模型相关联,我如何将 User 表中的 userId 链接到 post 表中的帖子?
    猜你喜欢
    • 1970-01-01
    • 2015-07-16
    • 2015-03-26
    • 2017-08-24
    • 1970-01-01
    • 2013-05-27
    • 2015-11-03
    • 2020-04-15
    • 1970-01-01
    相关资源
    最近更新 更多