Backend - sequelize: 다른 테이블 데이터 가져오기

BigbrotherShin·2020년 3월 24일
0

Backend

목록 보기
5/15
post-thumbnail
post-custom-banner

include를 통해 다른 테이블의 데이터를 가져올 수 있다.

attributes를 통해 데이터의 가져올 column을 선택할 수 있다.

예제

Post 테이블의 데이터를 가져오면서 User의 id와 nickname
Comment테이블의 id와 작성자의 nickname 데이터를 가져오는 예제를 살펴보자.

backend/models/post.js

module.exports = (sequelize, DataTypes) => {
  const Post = sequelize.define(
    'Post',
    {
      content: {
        type: DataTypes.TEXT, // 매우 긴 글은 TEXT로
        allowNull: false,
      },
    },
    {
      charset: 'utf8mb4', // 한글 + 이모티콘
      collate: 'utf8mb4_general_ci',
    },
  );

  Post.associate = db => {
    db.Post.belongsTo(db.User); // belongsTo가 있는 테이블에 다른 테이블의 id를 저장(Post 테이블에 UserId 저장)
    db.Post.hasMany(db.Comment);
  };

  return Post;
};

backend/routes/posts.js

router.get('/', async (req, res, next) => {
  // GET /api/posts
  try {
    const posts = await db.Post.findAll({
      include: [
        {
          model: db.User,
          attributes: ['id', 'nickname'],
        },
        {
          model: db.Comment,
          include: [
            {
              model: db.User,
              attributes: ['id', 'nickname'],
            },
          ],
          attributes: ['id', 'content'],
        },
      ],
    });
    console.log('POSTS: ', posts);
    return res.status(200).json(posts);
  } catch (e) {
    console.error(e);
    next(e);
  }
});

결과

console.log('POSTS: ', posts)

POSTS:  [
  Post {
    dataValues: {
      id: 14,
      content: 'zxcvzxcv',
      createdAt: 2020-03-24T13:59:34.000Z,
      updatedAt: 2020-03-24T13:59:34.000Z,
      UserId: 1,
      ReweetId: null,
      User: [User],
      Comments: []
    },
    _previousDataValues: {
      id: 14,
      content: 'zxcvzxcv',
      createdAt: 2020-03-24T13:59:34.000Z,
      updatedAt: 2020-03-24T13:59:34.000Z,
      UserId: 1,
      ReweetId: null,
      User: [User],
      Comments: []
    },
    _changed: {},
    _modelOptions: {
      timestamps: true,
      validate: {},
      freezeTableName: false,
      underscored: false,
      paranoid: false,
      rejectOnEmpty: false,
      whereCollection: null,
      schema: null,
      schemaDelimiter: '',
      defaultScope: {},
      scopes: {},
      indexes: [],
      name: [Object],
      omitNull: false,
      charset: 'utf8mb4',
      collate: 'utf8mb4_general_ci',
      sequelize: [Sequelize],
      hooks: {}
    },
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      include: [Array],
      includeNames: [Array],
      includeMap: [Object],
      includeValidated: true,
      attributes: [Array],
      raw: true
    },
    isNewRecord: false,
    User: User {
      dataValues: [Object],
      _previousDataValues: [Object],
      _changed: {},
      _modelOptions: [Object],
      _options: [Object],
      isNewRecord: false
    },
    Comments: []
  },
  Post {
    dataValues: {
      id: 15,
      content: 'zxvzxcv',
      createdAt: 2020-03-24T14:43:57.000Z,
      updatedAt: 2020-03-24T14:43:57.000Z,
      UserId: 1,
      ReweetId: null,
      User: [User],
      Comments: []
    },
    _previousDataValues: {
      id: 15,
      content: 'zxvzxcv',
      createdAt: 2020-03-24T14:43:57.000Z,
      updatedAt: 2020-03-24T14:43:57.000Z,
      UserId: 1,
      ReweetId: null,
      User: [User],
      Comments: []
    },
    _changed: {},
    _modelOptions: {
      timestamps: true,
      validate: {},
      freezeTableName: false,
      underscored: false,
      paranoid: false,
      rejectOnEmpty: false,
      whereCollection: null,
      schema: null,
      schemaDelimiter: '',
      defaultScope: {},
      scopes: {},
      indexes: [],
      name: [Object],
      omitNull: false,
      charset: 'utf8mb4',
      collate: 'utf8mb4_general_ci',
      sequelize: [Sequelize],
      hooks: {}
    },
    _options: {
      isNewRecord: false,
      _schema: null,
      _schemaDelimiter: '',
      include: [Array],
      includeNames: [Array],
      includeMap: [Object],
      includeValidated: true,
      attributes: [Array],
      raw: true
    },
    isNewRecord: false,
    User: User {
      dataValues: [Object],
      _previousDataValues: [Object],
      _changed: {},
      _modelOptions: [Object],
      _options: [Object],
      isNewRecord: false
    },
    Comments: []
  }
]
profile
JavaScript, Node.js 그리고 React를 배우는
post-custom-banner

0개의 댓글