具有restful-sequelize和mysql的节点js中的嵌套关​​联

时间:2015-09-28 21:24:10

标签: mysql node.js rest express sequelize.js

我正在尝试使用restful-sequelize和express在节点js中构建restful-apis。 我有两个表,分类和产品。我希望我的获取类别的URL返回类别,其中包含与之关联的产品列表。 对于例如/ api / categories应该返回 -

 [{"category_id":1,"name":"kids", "products":[/*list of products*/]}]

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

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

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);

1 个答案:

答案 0 :(得分:0)

我自己解决的问题如下:     首先修复关联:

Category.hasMany(Product, {
as: 'products',
foreignKey: 'categoryCategoryId'});

然后:

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)});