sequelize.js关联访问器

时间:2018-07-18 05:16:23

标签: node.js sequelize.js

我用Node.js制作了API服务器

我还使用sequelize.js(第4版)与MySQL进行通信。

我的表结构在这里。

  

[文章]

     
      
  • 没有(PK)
  •   
  • 主题
  •   
  • 内容
  •   
  • created_at
  •   
  • updated_at
  •   
     

[评论]

     
      
  • 没有(PK)
  •   
  • 内容
  •   
  • created_at
  •   
  • updated_at
  •   
  • article_no(从FK到Article)
  •   

[index.controller.js]

import { Article, Comment } from '../model/model';

export const index = (req, res) => {
    res.send('controller index');
};


export const getArticle = (req, res) => {
    try {
        Article.all()
        .then(article => {
            res.status(200).json({status: true, result: article});
        });
    } catch(e) {
        res.status(500).json({status: false, result: "get article fail"});
    }
}
export const addArticle = (req, res) => {
    const { subject, content } = req.body;
    try {
        Article.create({
            subject: subject,
            content: content
        })
        res.status(200).json({status: true, result: "article write success"});
    } catch(e) {
        res.status(500).json({status: false, result: "article fail"});
    }
}
export const getComment = (req, res) => {
    try {
        Comment.all()
        .then(comment => {
            res.status(200).json({status: true, result: comment})
        });
    } catch(e) {
        res.status(500).json({status: false, result: "get comment fail"});
    }
}
export const addComment = (req, res) => {
    const { content, article_no } = req.body;
    try {
        Comment.create({
            content: content,
            article_no: article_no
        })
        .then(() => res.status(200).json({status: true, result: "comment write success"}))
    } catch(e) {
        console.log(e);
        res.status(500).json({status: false, result: "comment fail"});
    }
}

[index.js]

import express from 'express';
import { index, getArticle, getComment,addArticle, addComment } from './index.controller';
const router = express.Router();

router.get('/', index);

router.get('/article', getArticle);
router.post('/article', addArticle);
router.get('/comment', getComment);
router.post('/comment', addComment);

export default router;

[model.js]

import Sequelize from 'sequelize';

const sequelize = new Sequelize('db', 'id', 'pw', {
    host: '127.0.0.1',
    dialect: 'mysql'
})

export const Article = sequelize.define('article', {
    no: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    subject: {
        type: Sequelize.STRING,
        allowNull: false
    },
    content: {
        type: Sequelize.STRING,
        allowNull: false
    }
}, {
    freezeTableName: true,
    underscored: true
})

export const Comment = sequelize.define('comment', {
    no: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    content: {
        type: Sequelize.STRING,
        allowNull: false
    }
}, {
    freezeTableName: true,
    underscored: true
})

Article.hasMany(Comment, {as: 'Comments'}); // association
Comment.belongsTo(Article); // association

sequelize.sync({
    force: false
});

由于关联(hasManybelongsTo),article_no列将添加到评论表。

请参阅本文档http://docs.sequelizejs.com/manual/tutorial/associations.html#one-to-many-associations-hasmany-

它说Instances of Project will get the accessors getWorkers and setWorkers.

在我的情况下,它将是getCommentssetComments

但是我不完全知道如何使用访问器获取所有与评论相关的文章。

电流输出在这里。 (如果我连接到GET /article

{  
   "status":true,
   "result":[  
      {  
         "no":1,
         "content":"comment test",
         "created_at":"2018-07-18T05:00:45.000Z",
         "updated_at":"2018-07-18T05:00:45.000Z",
         "article_no":1
      }
   ]
}

所需的输出在这里

{  
   "status":true,
   "result":[  
      {  
         "no":1,
         "content":"comment test",
         "created_at":"2018-07-18T05:00:45.000Z",
         "updated_at":"2018-07-18T05:00:45.000Z",
         "article_no":1,
         "comments": [
            // related comments here!
         ]
      }
   ]
}

谢谢。

1 个答案:

答案 0 :(得分:1)

要加入其他模型时,应在查询中使用包含

User.findAll({
  include: [
     { model: Profile, required: true // inner join }
  ],
  limit: 3
});

签出Sequelize model usage文档。

要使用访问者访问评论,您需要执行以下操作:

const articles = await Article.all();

articles.forEach(article => {
  const comments = await article.getComments();
})

背后的想法是,每个article序列对象都将具有访问器getComments,但是在内部执行getComments时它会做什么,它向数据库中的预填充{ {1}}在注释中查询。这称为延迟加载,因为您可以在需要时加载数据。但这不是你的情况。

对于所需的输出,我建议使用articleId方法,因为它将向数据库发出单个请求。