使用seqelize与hasMany关系postgresql来创build一个API

我在node.js之上使用了sequilize,并且为了创build一个可以使用本教程http://mherman.org/blog/2015/10/22/node-postgres-sequelize/#来访问的API 。 WSJ77BMrLBL 。 我不能让数据库填充一个名为商店与产品的对象。 我现在所拥有的是:

路线:

// 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"}当我导航到商店页面时,我得到了同样的东西,但无法看到productIds

我究竟做错了什么? 有人可以请提供一些指导。

谢谢!

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

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

所以它写道:

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

你的回应将有一个Products关键,这将是一个相关的产品arrays。