sequelize中的model.create时如何包含模型

时间:2019-10-25 21:32:31

标签: postgresql sequelize.js

我有一个添加帖子的功能,我该如何添加发表帖子的用户助理。现在它获得了作者ID,我希望它显示用户名

我知道使用Include,但这在使用fetchAll()时似乎有效

这是邮递员请求

enter image description here

我想在此发帖请求上附加用户。

这是发帖请求

  createPost: async (req: any, res: Response) => {
    // sorta hacky
    // const getUser = await models.Post.findOne({
    //   include: [{ model: models.User, as: "author", attributes: ["username"] }],
    //   where: {
    //     id: req.session.user.id
    //   },
    //   raw: true
    // });
    // console.log(getUser);

    await models.Post.create({
      title: req.body.title,
      postContent: req.body.postContent,
      authorId: req.session.user.id
    })
      .then(post => {
        res.status(200).send({
          message: "post created",
          post: post
        });
      })
      .catch(err => {
        res.status(401).send({
          message: `Something went wrong`,
          error: err
        });
      });
    console.log(req.body);
  }

0 个答案:

没有答案
相关问题