Как получить информацию о пользователе, а не просто установить ID?

Я использую sequelize с mysql,

У меня 3 модели

  1. сообщения
  2. Комментарии
  3. пользователи

модель постов

module.exports = (sequelize, DataTypes) => {
  const Post = sequelize.define('Post', {
    title: DataTypes.STRING,
    content: DataTypes.TEXT,
    userId: DataTypes.INTEGER
  }, {});
  Post.associate = function(models) {
    // associations can be defined here
    Post.hasMany(models.Comment, {
      foreignKey: 'postId',
      as: 'comments',
      onDelete: 'CASCADE',
    })
    Post.belongsTo(models.User, {
      foreignKey: 'userId',
      as: 'author',
      onDelete: 'CASCADE',
    })
  };
  return Post;
};

модель комментариев

const user = require("./user");

module.exports = (sequelize, DataTypes) => {
  const Comment = sequelize.define(
    "Comment",
    {
      postId: DataTypes.INTEGER,
      comment: DataTypes.TEXT,
      userId: DataTypes.INTEGER,
    },
    {}
  );
  Comment.associate = function (models) {
    // associations can be defined here
    Comment.belongsTo(
      models.User,
      {
        foreignKey: "userId",
        as: "author",
        me: "name",
      },
      { name: user.name }
    );
    Comment.belongsTo(models.Post, {
      foreignKey: "postId",
      as: "post",
    });
  };
  return Comment;
};

модель пользователей

module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define(
    "User",
    {
      name: DataTypes.STRING,
      email: DataTypes.STRING,
    },
    {}
  );
  User.associate = function (models) {
    // associations can be defined here
    User.hasMany(models.Post, {
      foreignKey: "userId",
      as: "posts",
      onDelete: "CASCADE",
    });

    User.hasMany(models.Comment, {
      foreignKey: "userId",
      as: "comments",
      onDelete: "CASCADE",
    });
  };
  return User;
};

и ниже мой ответ, который я получаю, когда выполняю следующий запрос

const getAllPosts = async (req, res) => {
  try {
    const posts = await models.Post.findAll({
      include: [
        {
          model: models.Comment,
          as: "comments"
        },
        {
          model: models.User,
          as: "author"
        }
      ]
    });
    return res.status(200).json({ posts });
  } catch (error) {
    return res.status(500).send(error.message);
  }
};

ОТКЛИК

 "posts": [
    {
      "id": 1,
      "title": "1st post ever on this server",
      "content": "This is the content of the first post published on this type or architecture",
      "userId": 1,
      "createdAt": "2021-01-31T10:00:45.000Z",
      "updatedAt": "2021-01-31T10:00:45.000Z",
      "comments": [
        {
          "id": 1,
          "postId": 1,
          "comment": "this is the comment on first post",


          "userId": 1, // Also need a key val pair of username and his email ID just instead of UserID


          "createdAt": null,
          "updatedAt": null
        },
        {
          "id": 2,
          "postId": 1,
          "comment": "comment second",
          "userId": 1,
          "createdAt": "2021-01-31T15:34:27.000Z",
          "updatedAt": "2021-01-31T15:34:27.000Z"
        }
      ],
      "author": {
        "id": 1,
        "name": "test user",
        "email": "[email protected]",
        "createdAt": null,
        "updatedAt": null
      }
    }
  ]
}

Мне нужно имя пользователя с прокомментированным именем пользователя и адрес электронной почты, для которого у меня есть поля в таблице, но я просто получаю идентификатор пользователя, как я могу это сделать, я очень новичок в сиквелизе, я пробовал, но получаю то же самое hasMany и benlongs к результатам.


person velocity CSGO    schedule 31.01.2021    source источник


Ответы (1)


Судя по тому, что вы делаете, вам нужно запустить вложенный include при получении комментария.

Попробуйте этот модифицированный код.

const getAllPosts = async (req, res) => {
  try {
    const posts = await models.Post.findAll({
      include: [
        {
          model: models.Comment,
          as: "comments",
          include: [
              {
              model: models.User,
              as: "author"
              }
           ]  
        },
        {
          model: models.User,
          as: "author"
        }
      ]
    });
    return res.status(200).json({ posts });
  } catch (error) {
    return res.status(500).send(error.message);
  }
};
person Samuel Chibuike    schedule 31.01.2021
comment
также что, если я хочу удалить определенный столбец, например, created at или updatedAt - person velocity CSGO; 31.01.2021
comment
вы можете использовать ключевое слово exclude {model: models.User, as: author, exclude: [createdAt, updatedAt]} - person Samuel Chibuike; 18.02.2021