2017-05-23 9 views
1

私は反応がこのチュートリアルhttp://mherman.org/blog/2015/10/22/node-postgres-sequelize/#.WSJ77BMrLBLを使用してアクセスできるAPIを作成するためにnode.jsの上にsequilizeを使用して表現しています。私は、データベースを商品と一緒にストアと呼ばれるオブジェクトで埋め込むことができません。私は今のよう持っていることは次のとおりです。sequelizeを使用してhasMany関係の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

thats、ありがとう!それが何か単純であることを知っていた – seanscal

関連する問題