2017-05-23 37 views
1

我在node.js之上使用sequilize并表示为了创建一个API,我的反应可以使用本教程http://mherman.org/blog/2015/10/22/node-postgres-sequelize/#.WSJ77BMrLBL访问。我无法让数据库填充名为商店的产品对象。我有什么作为的,现在是:使用sequelize创建具有许多关系的API postgresql

路线:

// get all stores 
router.get('/stores', function(req, res) { 
    models.Store.findAll({}).then(function(stores) { 
    res.json(stores); 
    }); 
}); 

// get single store 
router.get('/stores/:id', function(req, res) { 
    models.Store.find({ 
    where: { 
     id: req.params.id 
    } 
    }).then(function(store) { 
    res.json(store.productId); 
    }); 
}); 

// add new store 
router.post('/stores', function(req, res) { 
    models.Store.create({ 
    name: req.body.name, 
    productId: req.body.product_id 
    }).then(function(store) { 
    res.json(store); 
    }); 
}); 

店:

'use strict'; 
module.exports = function(sequelize, DataTypes) { 
    var Store = sequelize.define('Store', { 
    name: { 
     type: DataTypes.STRING, 
     defaultValue: "" 
    }, 
    description: { 
     type: DataTypes.STRING, 
     defaultValue: "" 
    }, 
    phone: { 
     type: DataTypes.STRING, 
     defaultValue: "" 
    }, 
    email: { 
     type: DataTypes.STRING, 
     defaultValue: "" 
    }, 
    image_url: { 
     type: DataTypes.STRING, 
     defaultValue: "" 
    }, 
    }, { 
    classMethods:{ 
     associate:function(models){ 
      Store.hasMany(models.Product, { foreignKey: 'productId'}); 
     } 
    } 
    }); 
    return Store; 
} 

但是当我运行curl --data "name=test&product_id=1" http://127.0.0.1:5000/stores

我得到: {"description":"","phone":"","email":"","image_url":"","id":2,"name":"test","updatedAt":"2017-05-22T05:43:10.376Z","createdAt":"2017-05-22T05:43:10.376Z"},当我浏览到商店页面我得到相同的东西,但看不到产品ID

我在做什么错?有人可以提供一些指导。

谢谢!

回答

3

Sequelize不会急于加载产品,除非您明确指出它包含关联的模型。将以下选项添加到您的models.Store.findById请求中。

const options = { 
    include: [{ 
     model: models.Product 
    }] 
}; 

,所以它读取:

models.Store.findById(req.params.id, options).then(... 

你的反应会产生Products关键,这将是相关产品的数组。

+0

多数民众赞成它,谢谢!知道这很简单 – seanscal

相关问题