首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用restful-sequelize和mysql的节点js中的嵌套关联

使用restful-sequelize和mysql的节点js中的嵌套关联
EN

Stack Overflow用户
提问于 2015-09-28 21:24:10
回答 1查看 635关注 0票数 0

我正在尝试使用restful-sequelize和express在node js中构建restful-apis。我有两个表,Category和Product。我想让我的get url返回Category以及与之相关的产品列表。例如,/api/类别应该返回-

代码语言:javascript
运行
AI代码解释
复制
 [{"category_id":1,"name":"kids", "products":[/*list of products*/]}]

我该怎么做呢?举个例子会有很大帮助。

我想可能我的关系没有正确定义,或者我需要修改findAll()方法。我的代码如下:

代码语言:javascript
运行
AI代码解释
复制
var express   = require('express')
  , bodyParser = require('body-parser')
  , Sequelize = require('sequelize')
  , http      = require('http')
  , Restful   = require('new-sequelize-restful')
  , sequelize = new Sequelize('test', 'root', 'root', {
        logging: console.log,
        define: {
            timestamps: false
        }
    })
  , app       = express();

var port = process.env.PORT || 3000;
app.use(bodyParser());

var Category = sequelize.define('categories', {
    category_id: {type:Sequelize.INTEGER, primaryKey:true},
    name: Sequelize.STRING
}); 

var Product = sequelize.define('products', {
    product_id: {type:Sequelize.INTEGER, primaryKey:true},
    name: Sequelize.STRING,
    description: Sequelize.STRING,
    price: Sequelize.FLOAT,
    categoryCategoryId: Sequelize.INTEGER
});

// Relationship definition
Category.hasMany(Product, {as:'products'});

app.all(/\/api\//, (new Restful(sequelize)).route());
app.listen(port);
console.log('Magic happens on port ' + port);
EN

回答 1

Stack Overflow用户

发布于 2015-11-26 09:57:55

我自己解决的方法如下:首先修复关联:

代码语言:javascript
运行
AI代码解释
复制
Category.hasMany(Product, {
as: 'products',
foreignKey: 'categoryCategoryId'});

然后:

代码语言:javascript
运行
AI代码解释
复制
Category.findAll({
include: [{
    model: Product,
    'as': 'products' //because you rename model Product on association with Category
}]}).then(function(response) {
console.log(response)}, function(err) {
console.log(err)});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32832068

复制
相关文章

相似问题

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