首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >sequelize.js关联访问器

sequelize.js关联访问器
EN

Stack Overflow用户
提问于 2018-07-18 05:16:22
回答 1查看 970关注 0票数 1

我用Node.js制作API服务器

此外,我还使用sequelize.js(版本4)与MySQL进行通信。

我的桌子结构在这里。

文章

  • 否(PK)
  • 主题
  • 内容
  • created_at
  • updated_at

评论

  • 否(PK)
  • 内容
  • created_at
  • updated_at
  • article_no(FK到条款)

index.controller.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
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)

代码语言:javascript
复制
{  
   "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
      }
   ]
}

期望的输出在这里

代码语言:javascript
复制
{  
   "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!
         ]
      }
   ]
}

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-18 05:59:04

当您想加入另一个模型时,应该在查询中使用include。

代码语言:javascript
复制
User.findAll({
  include: [
     { model: Profile, required: true // inner join }
  ],
  limit: 3
});

查看后缀模型使用文档。

要使用访问器访问注释,您需要执行如下操作:

代码语言:javascript
复制
const articles = await Article.all();

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

背后的想法是,每个article sequelize对象都有访问器getComments,但是在内部,当您执行getComments时,它会向数据库发出一个新的请求,并在注释where查询中使用预先填充的articleId。这称为延迟加载,因为您可以在需要时加载数据。但那不是你的案子。

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51394054

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档