Node.js 使用sequelize创建与postgresql有很多关系的API
我正在node.js和express之上使用sequilize,以便创建一个API,我的react可以使用本教程访问该API。我无法使用名为store with products的对象填充数据库。到目前为止,我拥有的是: 路线:Node.js 使用sequelize创建与postgresql有很多关系的API,node.js,postgresql,sequelize.js,Node.js,Postgresql,Sequelize.js,我正在node.js和express之上使用sequilize,以便创建一个API,我的react可以使用本教程访问该API。我无法使用名为store with products的对象填充数据库。到目前为止,我拥有的是: 路线: // get all stores router.get('/stores', function(req, res) { models.Store.findAll({}).then(function(stores) { res.json(stores
// 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\u 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
我做错了什么?有人能给我一些指导吗
谢谢 除非您明确告诉Sequelize包含关联的模型,否则Sequelize不会急于加载产品。将以下选项添加到您的
models.Store.findById
请求中
const options = {
include: [{
model: models.Product
}]
};
它是这样写的:
models.Store.findById(req.params.id, options).then( ...
您的响应将有一个Products
键,该键将是一个关联产品的数组