2017-04-14 7 views
0

最新の変更が確実に反映されるように、強制的に同期させながら、製品モデルとユーザーモデルを関連付けることを試みています。列UserIdとProductManagerIdが作成されないというエラーが表示されます。Sequelize Association Columnsが生成されません

なぜ列が自動生成されないのですか?

Product.js

'use strict'; 
/* Model ONLY for 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,{ as : 'ProductManager'}); 
     // associations can be 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 be defined here 
     User.hasMany(models.Product); 
     }, 
    }, 
    freezeTableName: true, 
    }); 
    // FORCE FOR NOW Use only if make model changes 
    User.sync({force: true}).then(() => { 
    console.log('Sequelize forced'); 
    }) 
    return User; 
}; 

方言:のPostgres Sequelizeバージョン: 3.30.1

Psと。私はもともと、モデルファイルを生成するためにsequelize-cliを使用し、次に私のニーズに変更しました。

答えて

0

私は間違っているかもしれません(または情報が不十分です)が、これは私のバグのようです。 Userモデルでは

いずれにせよ、あなたのモデルで以下の小さな変更を加えることで、あなたの問題を解決できる製品モデルで

// Note the addition of 'foreignKey' 
User.hasMany(models.Product, {as: 'ProductManager', foreignKey: 'ProductManagerId'}); 

を:

// Note the addition of 'foreignKey' 
Product.belongsTo(models.User,{ as : 'ProductManager', foreignKey: 'ProductManagerId'}); 

今商品表にはFOREIGN KEY (ProductManagerId) REFERENCES user (id) が必要です。すべて設定する必要があります。

関連する問題