MySQL Sequelize & Express-Phần 2 : One To Many

Link part 1 : MySQL Sequelize & Express-Phần 1 :Cài đặt và tạo table
Link part 2 : MySQL Sequelize & Express-Phần 2 : Building REST CRUD API

Ta tạo table comments dùng để lưu các comment của người dùng cho mỗi bài viết (news->many comments)
Tại file models/comment.model.js:

module.exports = (sequelize, Sequelize) => {
    const Comment = sequelize.define("comment", {
        name: {
            type: Sequelize.STRING
        },
        text: {
            type: Sequelize.STRING
        }
    });
    return Comment;
};

Sửa file models/index.js:
Ta thêm:

db.comments = require("./comment.model.js")(sequelize, Sequelize);
db.news.hasMany(db.comments, { foreignKey: "newId", as: "comments" });
db.comments.belongsTo(db.news, {
  foreignKey: "newId",
  as: "new",
});

Ở đây khóa ngoại là newId trong table comments
File models/index.js hoàn chỉnh:

Ta chạy lệnh npm start để tạo table comments

Thêm vào controllers/new.controller.js
Tạo Comments

exports.createComment = (req, res) => {

  if (!req.body.name) {
    res.status(400).send({
      message: "Name can not be empty!"
    });
    return;
  }

  const commentData = {
    name: req.body.name,
    text: req.body.text,
    newId: req.body.newId,
  };

  Comment.create(commentData)
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating comment."
      });
    });
};

Get the comments for a given new id

exports.findNewAndCommentByNewId  = (req, res) => {
  const newId = req.params.newId;

  New.findByPk(newId, { include: ["comments"] })
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message: "Error retrieving New with id=" + newId
      });
    });
};

Get the comments for a given comment id

exports.findCommentById = (req, res) => {
  const commentId = req.params.commentId;

  Comment.findByPk(commentId, { include: ["new"] })
    .then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message: " Error while finding comment id=" + commentId
      });
    });
};

Get all Tutorials include comments

exports.findAllNewAndComment = (req, res) => {
  New.findAll({
    include: ["comments"],
  }).then(data => {
      res.send(data);
    })
    .catch(err => {
      res.status(500).send({
        message: "Error retrieving all new and comment"
      });
    });
};

Thêm vào file routes/new.routes.js line 5:

router.get("/find-all-new-comment", news.findAllNewAndComment);

Thêm vào file routes/new.routes.js trước app.use(‘/api/news’, router);

// Create a comment
    router.post("/create-comment", news.createComment);

     // Retrieve a comments new with new id
    router.get("/find-comment-new/:newId", news.findNewAndCommentByNewId);

    // Retrieve a comments with id
    router.get("/find-comment-by-id/:commentId", news.findCommentById);

File new.routes.js hoàn chỉnh:

Test:
Tạo 1 new mới:
Link:localhost:8081/api/news
Method:Post

Kết quả trả về với id new=1

Tạo Comments với newid=1
Link:localhost:8081/api/news/create-comment
Method:Post

Get Comment and New by given new id
Link:localhost:8081/api/news/find-comment-new/1
Method:GET

Get Comment by given comment id
Link:localhost:8081/api/news/find-comment-by-id/1
Method:GET

Get all new
Link:localhost:8081/api/news/find-all-new-comment
Method:GET

Link code demo in here

Leave a Reply

avatar
  Subscribe  
Notify of