Node.js 第二个层次包括使用sequelize

Node.js 第二个层次包括使用sequelize,node.js,sequelize.js,Node.js,Sequelize.js,如果用户可以有许多帖子,并且每个帖子可以有许多图像,这是否意味着用户和图像是关联的?因为目前我正在尝试为每个用户显示这些帖子,对于这些帖子,我想使用上面提到的方法将图像显示为url和thumbnailurl。我一直收到一个错误,即Post_图像与用户不关联 我目前正在尝试这段代码,我不断得到一个错误,无法读取属性映射 router.get("/posts", auth, (req, res) => { let { id } = req.user; User.findB

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

我目前正在尝试这段代码,我不断得到一个错误,无法读取属性映射

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 });
 });
 });

在本例中,它类似于处理几个帖子,如

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


为什么这与使用findByPk时处理几个调用是一样的?最初,您询问了通过
Post.findAll
获得的Posts数组。如果在
include
optionokay中指示
Posts
,则与从用户模型实例获取
Posts
数组相同,现在我明白了原因,因为我正在尝试获取该用户的所有Posts,因此与findAll相同,再次感谢,我有一个关于这篇文章的问题,因为现在用户与文章关联了,我如何将用户表中的用户ID链接到文章表中的文章?嗨,Anatoly,我有一个关于你对这篇文章的解决方案的问题。既然我的用户模型与Post模型相关联,那么如何将用户表中的userId链接到Post表中的Post?
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);