node.js - Sequelize Association Columns not generated -
i'm trying associate products model user model while making sure force sync in order ensure newest changes present. error columns userid , productmanagerid not created.
why columns not auto-generated?
product.js
'use strict'; /* model depuy products */ module.exports = function(sequelize, datatypes) { var product = sequelize.define('product', { name: { type: datatypes.string, allownull : false }, sku: { type:datatypes.string, allownull: false, primarykey: true, }, }, { classmethods: { associate: function(models) { product.belongsto(models.user,{ : 'productmanager'}); // associations can defined here } } }); product.sync({force: true}).then(() => { console.log('sequelize forced'); }) return product; };
user.js
module.exports = (sequelize, datatypes) => { const user = sequelize.define('user', { id: { type: datatypes.integer, autoincrement: true, primarykey: true, allownull: false, }, password: { type: datatypes.string, allownull: false, }, email: { type: datatypes.string, unique: true, }, }, { classmethods: { associate: (models) => { // associations can defined here user.hasmany(models.product); }, }, freezetablename: true, }); // force use if make model changes user.sync({force: true}).then(() => { console.log('sequelize forced'); }) return user; };
dialect: postgres sequelize version: 3.30.1
ps. used sequelize-cli generate model file, changed needs.
i may wrong (or insufficiently informed), looks bug me.
in case, can fix issue making following small changes in models:
in user model:
// note addition of 'foreignkey' user.hasmany(models.product, {as: 'productmanager', foreignkey: 'productmanagerid'});
in product models:
// note addition of 'foreignkey' product.belongsto(models.user,{ : 'productmanager', foreignkey: 'productmanagerid'});
now, product table should have foreign key (productmanagerid) references user (id)
, should set go.
Comments
Post a Comment